Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gather divs and perform CSS on them: HTMLCollection vs Array

Wondering how I can make this work properly:

var ArrayTest = [1,2,3,4,"test"];
var ArrayTest2 = document.getElementsByClassName('mydiv');
ArrayTest2.forEach( function(){
    this.style.display = 'none'; 
});

So ArrayTest comes back as an Array, but ArrayTest2 comes back as an HTMLCollection and forEach throws an "undefined" type error.

How can I collect an array of elements that all have the same classname and then perform the same CSS on each one?

like image 216
RenaissanceProgrammer Avatar asked Dec 19 '22 13:12

RenaissanceProgrammer


1 Answers

I would do this a slightly different way, by adding a CSS class, and probably by using jQuery to make your life easier:

$(".mydiv").addClass("no-display");

then in your CSS

.no-display {
    display: none;
}

If you want to assign the specific inline attribute then you could use:

$(".mydiv").css("display", "none");

edit

Ok so for a pure JavaScript approach

for (var i = 0; i < ArrayTest2.length; i++) {
   ArrayTest2[i].style.display = "none"; 
}
like image 175
Ian Avatar answered Dec 24 '22 00:12

Ian