How to get, set or change CSS using jQuery css method

Hello guys,

Sometimes you need to add or change CSS after Javascript events fire, For example clicks, hover. Using jQuery, you can simply change CSS to any elements. Or you might want to get CSS for the selected element based on condition.

In this article, I will show you how you can add new CSS, change or get CSS of any element using jQuery. jQuery has css() method which is used to manipulate CSS.

Syntax:

$(selector).(propertyname, propertyvalue);

Example:

In the below example, first p element has style background-color:green and second p element doesn't have any background-color property. If the property doesn't have any property name, it will set property value else it will change CSS for the selected all elements.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h1>jQuery css() method</h1>
    <p style="background-color: green;">This element have background-color property as green</p>
    <p>This element doesn't have any background-color property</p>
    <button id="btn">Change background-color property</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('button').on('click', function() {
                $('p').css('background-color', 'red');
            });
        });
    </script>
</body>
</html>

If you want to find any property value for the selected element, remove second parameter. If there are more than one matched selector, it will return property value from first matched selector. If the selected element doesn't has any property, then it will return default value.

Syntax:

$(selector).(propertyname);

Below example will return the property value for the first p element.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h1>jQuery css() method</h1>
    <p>This element doesn't have any background-color property</p>
    <p style="background-color: green;">This element have background-color property as green</p>
    <button id="btn">Get background-color property</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('button').on('click', function() {
                var bgColor = $('p').css('background-color');
                alert('p element has background-color property as '+bgColor);
            });
        });
    </script>
</body>
</html>

I hope it will help you.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment