JavaScript – Change the Background Color of Paragraph

To change the background color of a paragraph using JavaScript, get the reference to the element, and assign the specific color to the element.style.backgroundColor property.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head> 
<body>
    <p id="myPara">Change the Background Color of Paragraph in JavaScript</p>
    <button type="button" onclick="changeBackground()">Click Me</button>
    <script>
    function changeBackground(){
        var element = document.getElementById("myPara");
        element.style.backgroundColor = "green";
        //element.style.backgroundColor = "#00FF00";
    }
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to change the background color of a paragraph using JavaScript.