Tutorials using JS
Change background color of Paragraph using JavaScript
In this tutorial, you shall learn how to change background color of paragraph element using JavaScript.
Solution
To set or change the background color of a paragraph element using JavaScript, we can use Element.style.background
property. Get the paragraph element and set its style.background
property with the required color value.
paragraphElement.style.background = 'yellow';
paragraphElement.style.background = '#CCFFCC';
Programs
We get the paragraph with the id message
and set its background color using style.background
property.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="message">This is a paragraph. Welcome to JavaScript tutorials.</p>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
//get the paragraph element
const myPara = document.getElementById("message");
//set the background color of the paragraph
myPara.style.background = 'yellow';
});
</script>
</body>
</html>