Home >Web Front-end >JS Tutorial >How can I change the background color of a webpage using JavaScript?

How can I change the background color of a webpage using JavaScript?

DDD
DDDOriginal
2024-11-14 18:39:02682browse

How can I change the background color of a webpage using JavaScript?

Altering the Background Color with JavaScript

Changing the background color of a webpage with JavaScript is a straightforward task. Here's how to do it:

Solution:

  1. Access the document body: Utilize the document.body property.
  2. Modify the background style: Set the background property of document.body.style. For instance, to set it to red, use document.body.style.background = 'red'.

Here's a sample function to achieve this:

function changeBackground(color) {
   document.body.style.background = color;
}

Toinvoke the function, add the following code to the page's onload event handler:

window.addEventListener("load",function() { changeBackground('red') });

Note:

Consider the page's structure. If the background is set to a specific DIV container, you need to modify its background color instead of the document body.

The above is the detailed content of How can I change the background color of a webpage using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn