JavaScript Code

How to change background color of paragraph using JavaScript?


Tutorials using JS

Problem Statement

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>


Copyright @2022