Skip to content Skip to sidebar Skip to footer

Getelementsbyclassname Doesn't Work

I try to hide some HTML elements onload and then show and manipulate them. The code works fine when I use element's individual IDs with getElementById() method. But when I try to d

Solution 1:

You cannot apply properties in bulk like that. This is why using jQuery is preferred for things like this:

$('.MyModal99').css('display', 'none');

If you want to do this without jQuery:

var nodes = document.getElementsByClassName("MyModal99");
for(var i = 0; i < nodes.length; i++) {
  nodes[i].style.display = 'none';
}

Solution 2:

It's because getElementsByClassName() returns an array-like object of elements. You need to access a specific element in order to change the style object.

You could iterate over the elements:

var elements = document.getElementsByClassName("MyModal99");
Array.prototype.forEach.call(elements, function (el) {
  el.style.display = 'none';
});

or:

var elements = document.getElementsByClassName("MyModal99");
for (var i = 0; i < elements.length; i++) {
  elements[i].style.display = 'none';
}

Solution 3:

document.getElementsByClassName returns an array, which doesn't have a "style" property. You need to iterate over the array:

functionHideModals() {
        //document.getElementById("p1").style.display = 'none';//document.getElementById("p2").style.display = 'none';var modals = document.getElementsByClassName("MyModal99");
        for (var i=0; i < modals.length; i++) {
            modals[i].style.display = 'none';
        }
    }    

Solution 4:

The issue here is that document.getElementsByClassName("MyModal99") returns a list of items, so you'd have to loop through them and apply your properties one at a time. Something like this:

var elements = document.getElementsByClassName("MyModal99");
for ( var e in elements ) {
    e.style.display = "none";
}

If you need to support older browsers, do it the old fashioned way without a for..in loop:

var elements = document.getElementsByClassName("MyModal99");
for ( var i = 0 ; i < elements.length ; ++i ) {
    elements[i].style.display = "none";
}

Solution 5:

Thats because document.getElementsByClassName returns an array of nodes. You need to iterate each of the returned nodes to set their styles individually.

var eleArray = document.getElementsByClassName('MyModal99');

for(var i = 0; i < eleArray.length; i++) {
    eleArray[i].style.display = 'none';
}

Post a Comment for "Getelementsbyclassname Doesn't Work"