Open In App

How to set the background color of the specified elements using jQuery ?

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to set the background color of specific elements using jQuery.To set the background-color, we use css() method.

The css() method in jQuery is used to get or set CSS properties of selected elements. It allows you to retrieve the value of a CSS property or modify it by passing property names and values as arguments this method helps us to add CSS properties dynamically

Syntax : 

$("tag-name").css("property-name", "value");

Approach: We have created three elements inside the body tag i.e. <h1>, <h2> and <p> elements. We apply CSS property on all the elements i.e. <h1>, <h2> and <p>.

Example 1: In this example, we are going to use CSS() method which sets the background color to our elements dynamically.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,
                                   initial-scale=1.0">
    <script src=
    </script>
    <script>
        $(document).ready(function(){
           $("h1").css("background-color" ,  "red");
           $("h2").css("background-color" ,  "yellow");
           $("p").css("background-color" ,  "green");
        });
    </script>
</head>
<body>
    <h1>Hello GeeksforGeeks</h1>
    <h2>Hello Geeks</h2>
    <p>How Are You!!</p>
 
</body>
</html>


Output:

background-color

Example 2: In this example, we are going to use the addClass() method to set the background color of the elements.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,
                                   initial-scale=1.0">
    <script src=
    </script>
    <script>
        $(document).ready(function(){
            $("h1").addClass("first");
            $("h2").addClass("second");
            $("p").addClass("third");
         });
    </script>
    <style>
        .first{
            background-color:green;
        }
        .second{
            background-color:orange;
        }
        .third{
            background-color:violet;
        }
    </style>
</head>
<body>
    <h1>Hello GeeksforGeeks</h1>
    <h2>Hello Geeks</h2>
    <p>How Are You!!</p>
 
</body>
</html>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads