简体   繁体   中英

Iterating over DOM element

I am iterating DOM elements using a for loop, using 2 syntax and in both I am getting different results.

The JavaScript method 1 is

for (var sortable in document.getElementsByClassName('test')) {
           console.log("---- " + sortable)
           sortable.setAttribute('class', '');
    }

Th output for this gives error

undefined is not a function

for sortable.setAttribute('class', ''); line.

And using javascript 2 method

   var elements = document.getElementsByClassName("test");

   for (var i=0; i< elements.length;i++) {
         elements[i].setAttribute("class", "");
   }

I get the appropriate result.

My html code is

       <span class="test" id="test1">Test1 </span>
        <span class="test" id="test2">Test2 </span>
        <span class="test" id="test3">Test3 </span>

I don't know why I don't get DOM elements in var sortable in document.getElementsByClassName('test') as sortable ?

If you do a for .. in loop in JavaScript, it is important to know that the value returned by the for loop is actually the key and not the value.

So you could try this:

var testElements = document.getElementsByClassName('test');

for (var key in testElements) {
    var sortable = testElements[key];
    console.log("---- " + sortable)
    sortable.setAttribute('class', '');
}

However, this would fail as there are many properties defined on the value returned by getElementsByClassName , which not all return an element.

You can see them all by doing the following:

for (var key in document.getElementsByClassName('test')) {
    console.log(key);
}

This will output something like this:

0
1
2
test1
test2
test3
length
item
namedItem

You can see that not only does the returned value contain the numerical indexes, it also has the ID's as properties and also an item and namedItem property.

Unfortunatety, your for-loop also doesn't work as you are changing the class name and getElementsByClassName returns a "live" collection, which means that once you change the class, it is removed from the collection.

You can work around this with a simple loop:

var elements = document.getElementsByClassName("test");

while (elements.length > 0) {
    elements[0].setAttribute("class", "");
}

This solution was taken from: Javascript For Loop execution on dom element

getElementsByClassName returns an array of all the elements.

For-in only iterates over objects, not arrays.

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