Javascript For Loop execution on dom element -


this question has answer here:

i have javascript code elements class name , iterate on remove class elements.

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

and there 3 span class name "test". html code

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

but getting 2 class removed. second span class still remains there.

the console output is

length 3

---- 0

---- 1

getelementsbyclassname returns live htmlcollection object, gets updated when remove class elements.

so 1 simple logic can use use while loop , see if collection has items, if remove class first item.

function removeclass() {    var elements = document.getelementsbyclassname("test");    console.log("length " + elements.length)    while (elements.length) {      elements[0].setattribute("class", "");    }  }
.test {    color: red;  }
<span class="test" id="test1">test1 </span>  <span class="test" id="test2">test2 </span>  <span class="test" id="test3">test3 </span>  <button onclick="removeclass()">test</button>


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] -