Sake
Sake

Reputation: 655

Can't set styles to elements with a specified class javascript

This is my javascript code:

document.getElementsByClassName('loader').style.opacity = "0";

this code will give an error in my console displayed below:

TypeError: 'undefined' is not an object (evaluating 'document.getElementsByClassName('loader').style.opacity = "0"')

I have already tried these, but these also do not work:

document.document.querySelectorAll('.loader').style.opacity = '0';
document.document.querySelector('.loader').style.opacity = '0';

My html code:

<div class="loader">Some Text</div>

Upvotes: 0

Views: 1884

Answers (2)

Dropout
Dropout

Reputation: 13876

If you select elements by classes you most will most likely end up with an array of elements. You need to set the parameters for each one. Pure JS doesn't behave as jQuery regarding this.

First make your selection by

var elements = document.getElementsByClassName('loader');

then cycle through them

for(var i=0; i<elements.length; i++){
    elements[i].style.opacity = "0";
}

See if this helps..

Upvotes: 0

Pointy
Pointy

Reputation: 414086

The .getElementsByClassName() function returns a list of elements. You have to iterate over that list with your own code.

var loaders = document.getElementsByClassName('loader');
for (var i = 0; i < loaders.length; ++i)
  loaders[i].style.opacity = '0';

If you just want to operate on particular members of the list, you can (if you're careful) treat it like an array. I mention being careful because .getElementsByClassName() returns a "live" NodeList. If you remove the class "loader" from one or more of the elements, the list will change. (That's not the case for the lists returned from .querySelectorAll().)

Upvotes: 1

Related Questions