Open In App

Get the numeric part of CSS property using jQuery

Given a HTML document, The task is to get the numeric part of the CSS properties. Like if margin-top = 10px we want to extract only 10. Here few of the methods discussed. First few methods to understand.

$(selector).on(event, childSel, data, fun, map)
$(selector).text()
$(selector).text(content)
$(selector).text(function(index, curContent))
css("propertyname")
css("propertyname", "value")
css({"propertyname":"value", "propertyname":"value", ...});
string.replace(searchVal, newvalue)

Example 1: This example selects the element and then extracts its property using .css() method, a RegExp and replace() method






<!DOCTYPE html>
<html>
 
<head>
    <title>
        JQuery | Get numeric part of CSS property.
    </title>
    <style>
        #GFG_UP {
            font-size: 17px;
            font-weight: bold;
        }
         
        #GFG_DOWN {
            color: green;
            font-size: 24px;
            font-weight: bold;
        }
         
        button {
            margin-top: 20px;
        }
    </style>
</head>
</script>
 
<body style="text-align:center;" id="body">
    <h1 style="color:green;">
            GeeksforGeeks
        </h1>
    <p id="GFG_UP">
    </p>
    <button>
        click here
    </button>
    <p id="GFG_DOWN">
    </p>
    <script>
        $('#GFG_UP').text('Click on the button to get numeric value from CSS property');
        $('button').on('click', function() {
            var data = $('button').css('marginTop').replace(/[^-\d\.]/g, '');
            $('#GFG_DOWN').text("Value of marginTop property of button = " + data);
        });
    </script>
</body>
 
</html>

Output:

Example 2: This example selects the element with [id = ‘GFG_UP’] and then extracts its fontSize property using .css() method, a RegExp and replace() method






<!DOCTYPE html>
<html>
 
<head>
    <title>
        JQuery | Get numeric part of CSS property.
    </title>
    <style>
        #GFG_UP {
            font-size: 17px;
            font-weight: bold;
        }
         
        #GFG_DOWN {
            color: green;
            font-size: 24px;
            font-weight: bold;
        }
         
        button {
            margin-top: 20px;
        }
    </style>
</head>
</script>
 
<body style="text-align:center;" id="body">
    <h1 style="color:green;">
            GeeksforGeeks
        </h1>
    <p id="GFG_UP">
    </p>
    <button>
        click here
    </button>
    <p id="GFG_DOWN">
    </p>
    <script>
        $('#GFG_UP').text('Click on the button to get numeric value from CSS property');
        $('button').on('click', function() {
            var data = $('#GFG_UP').css('fontSize').replace(/[^-\d\.]/g, '');
            $('#GFG_DOWN').text("FontSize property of element[id = 'GFG_UP'] = " + data);
        });
    </script>
</body>
 
</html>

Output:


Article Tags :