How to set the background color of the specified elements using jQuery ?
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. This method helps us to add CSS properties dynamically.
Syntax :
$("tag-name").css("property-name", "value");
Approach: We have created three elements inside 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:
Please Login to comment...