Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach processes array of DOM elements through an one

I encountered a strange behavior of simple JS code. Elements processed through an one.

var a = document.getElementsByClassName('nahren');
Array.prototype.forEach.call(a, function(e) {
    e.classList.remove('nahren')
})

Example on JSFiddle

like image 864
Kesantielu Dasefern Avatar asked Dec 08 '22 20:12

Kesantielu Dasefern


2 Answers

Collections returned by getElementsByClassName are "live": if you change them to disqualify them from the selector, they disappear from the collection. This makes iterating over them wonky. Use querySelectorAll('.nahren'), which returns a "dead" collection, or pin the "live" collection by cloning it:

var deadArray = Array.prototype.slice.call(liveCollection);
deadArray.forEach(...)
like image 93
Amadan Avatar answered Dec 11 '22 10:12

Amadan


Amadan, has already answered correctly, but here is another implementation in which you can clone them using ES6.

var a = Array.from(document.getElementsByClassName('nahren')); //clone array
Array.prototype.forEach.call(a, function(e,i) {
  e.classList.remove('nahren');
})
div#container div {
  height: 30px;
  width: 100px;
  margin-bottom: 5px;
}

.hren {
  outline: 1px red solid;
}

.hren.nahren {
  outline: 1px blue solid;
}
<div id="container">
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
<div class="hren nahren"></div>
  <div>
like image 34
A.T. Avatar answered Dec 11 '22 10:12

A.T.