How to Change Background Color using JavaScript
Table of Contents
Even though CSS is the preferred language for making style changes, you can still make style changes using JavaScript.
A commonly-altered property is the background color of a page, as it can instantly change the entire look and feel of a website.
In this post, we'll look at how to use JavaScript to change the background color of a page or element.
Changing the Background Color of a Page
Every element has a style
property, which is a JavaScript object that contains all of the CSS properties that can be applied to that element.
One of these properties is the background
property, which is used to change the background color of an element.
To change the color of the background of the body, we can use the following code:
JAVASCRIPTdocument.body.style.background = "blue";
Try this example for yourself:
- JavaScript
Changing the Background Color of an Element
The body is just like any other element, meaning if you can change the background color of the body, you can change the background color of any element.
To change the background color of an element, first query for it.
JAVASCRIPTconst element = document.querySelector(".element");
Then, just like before, we can change the background color of the element using the background
property:
JAVASCRIPTelement.style.background = "red";
Then, we can change the background color of the element using the style
property.
JAVASCRIPTelement.style.background = "blue";
The attribute also supports hexadecimal colors as well:
JAVASCRIPTelement.style.background = "#00ff00";
Conclusion
In this post, we learned how to use JavaScript to change the background color of a body or any element.
Just get the element you want to change then set a new value on its style
property.
Thanks for reading and happy coding!
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js