Gather divs and perform CSS on them: HTMLCollection vs Array

arrays, css, html, javascript

Solution

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"; 
}

Problem

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?

Original source