rufus
rufus

Reputation: 857

Adding class on load with javascript not working

I am trying to add a class on page load using javascript. I'm currently learning javascript so bear with me. I am just trying to change the background color of an element as a test shown below. I get the error "Uncaught TypeError: Cannot read property 'classList' of null"

I know I am more than likely missing a very simple step here so would appreciate any advice.

Thanks all

window.onload = onPageLoad();

function onPageLoad() {
    document.querySelector('.home').classList.add = ('active');
}
.bg-yellow {
  background-color: yellow;
}

.active {
  background-color: green;
}

div {
  height: 400px;
  width: 400px;
}
<div class="bg-yellow"></div>

Upvotes: 0

Views: 1355

Answers (2)

Code_Frank
Code_Frank

Reputation: 381

Remove the = sign. As I recall, .add () is a function. Also search .bg-yellow, not .home in the querySelector function, assuming that is what you want to add the class to given your code samples. Or add 'home' to the classes of the .bg-yellow div e.g.

<div class='bg-yellow home'><div>.

The error you are receiving is because .home does not exist in your page according to the sample you gave. Therefore the .querySelector will return null (see the standard) when searching for that selector, and there is no classList defined for null objects.

Upvotes: 1

Asons
Asons

Reputation: 87211

First, remove () from window.onload = onPageLoad(); when assign, or else it will invoke it immediately.

Second, it should be .classList.add('active');, not .classList.add = ('active');.

Third, your element's class selector is .bg-yellow, not .home.

Stack snippet

window.onload = onPageLoad;

function onPageLoad() {
    document.querySelector('.bg-yellow').classList.add('active');
}
.bg-yellow {
  background-color: yellow;
}

.active {
  background-color: green;
}

div {
  height: 400px;
  width: 400px;
}
<div class="bg-yellow"></div>

Upvotes: 3

Related Questions