Set Background Color for HTML Element(s) using jQuery
Selected some HTML elements in the document, set background color for the elements using jQuery.
Solution
To set background color for selected HTML elements using jQuery, call css() function on the selected elements and pass the arguments: "background-color"
CSS property, and required color value.
For example, the syntax to set yellow color as background color for all paragraphs in the document is
$("p").css("background-color", "yellow");
Programs
1. Set background color to yellow for paragraphs in the document.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
function myAction() {
$("p").css("background-color", "yellow");
}
</script>
</head>
<body>
<button onclick="myAction()">Set yello background color for paragraphs</button>
<p>This is paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
2. Set background color to yellow for div element with id myDiv
, in the document.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
function myAction() {
$("div#myDiv").css("background-color", "yellow");
}
</script>
</head>
<body>
<button onclick="myAction()">Set yello background color for div</button>
<div id="myDiv" style="width:200px;height:200px">This is a div.</div>
</body>
</html>