Reputation: 2400
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
?
Upvotes: 0
Views: 82
Reputation: 16636
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
Upvotes: 3
Reputation: 21
getElementsByClassName returns an array of all the elements.
For-in only iterates over objects, not arrays.
Upvotes: 0