javascript - Iterating over DOM element -


i iterating dom elements using loop, using 2 syntax , in both getting different results.

the javascript method 1

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

th output gives error

undefined not function

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

and using javascript 2 method

   var elements = document.getelementsbyclassname("test");     (var i=0; i< elements.length;i++) {          elements[i].setattribute("class", "");    } 

i appropriate result.

my html code

       <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 don't dom elements in var sortable in document.getelementsbyclassname('test') sortable?

if for .. in loop in javascript, important know value returned loop key , not value.

so try this:

var testelements = document.getelementsbyclassname('test');  (var key in testelements) {     var sortable = testelements[key];     console.log("---- " + sortable)     sortable.setattribute('class', ''); } 

however, fail there many properties defined on value returned getelementsbyclassname, not return element.

you can see them doing following:

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

this output this:

 0 1 2 test1 test2 test3 length item nameditem 

you can see not returned value contain numerical indexes, has id's properties , item , nameditem property.

unfortunatety, for-loop doesn't work changing class name , getelementsbyclassname returns "live" collection, means once change class, removed collection.

you can work around simple loop:

var elements = document.getelementsbyclassname("test");  while (elements.length > 0) {     elements[0].setattribute("class", ""); } 

this solution taken from: javascript loop execution on dom element


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -