简体   繁体   中英

Looping through JavaScript "getElementsByTagName()" object

How can I loop through an object returned from "getElementsByTagName()" on a selector correctly. I can't seem to get it right.

For example, if I have a bunch of divs like this:

<div class="wrapper">
<div class="test1">this is a div</div>
<div class="test2">this is a div</div>
<div class="test1">this is a div</div>
<div class="test2">this is a div</div>
<div class="test1">this is a div</div>
<div class="test2">this is a div</div>
</div>

and I want to loop through the results from a "getElementsByTagName()" like this:

var wrapper = document.querySelector(".wrapper");

var divs = wrapper.getElementsByTagName("div");

for (i = 0; i < divs.length; ++i) {
   each = divs[i];
   if (each.classList.contains("test2")) {
    this.style.display = "none";
   }
}

and here's a fiddle : http://jsfiddle.net/Y2Yzv/1/

You have an error in the console: Uncaught TypeError: Cannot set property 'display' of undefined

Try:

var wrapper = document.querySelector(".wrapper");

var divs = wrapper.getElementsByTagName("div");

for (i = 0; i < divs.length; ++i) {
   each = divs[i];
   if (each.classList.contains("test2")) {
    each.style.display = "none";
   }
}

Demo

each.style.display = "none"; would work instead of this

this refers to the global object, and not to the element being iterated in your loop.

Here is corrected fiddle:

http://jsfiddle.net/Y2Yzv/4/

Less code solution:

var divs = document.querySelectorAll('.wrapper div');
[].forEach.call(divs, function (div) {
    if (div.classList.contains('test2')) div.style.display = 'none';
});

Change this.style.display = "none"; to each.style.display = "none"

Check this solution: http://jsfiddle.net/ZffWg/

These are the main changed I've made

for (i in divs) {
    if (divs[i].className.indexOf("test2") > -1) {
        divs[i].style.display = "none";
    }
}

I removed the i=0 and so the loop runs on the array index itself.

I also used className instead of classList for better cross-platform compatibility

 let divs_in_wrapper = document.querySelectorAll('.wrapper div'); divs_in_wrapper.forEach((item, index, arr) => { if (item.classList.contains("test2")) { item.style.display = "none"; } });
 <div class="wrapper"> <div class="test1">this is a div</div> <div class="test2">this is a div class test2</div> <div class="test1">this is a div</div> <div class="test2">this is a div class test2</div> <div class="test1">this is a div</div> <div class="test2">this is a div class test2</div> </div> <div class="test2">this is outside a div</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM