DOM - Collection Iteration (NodeList, ..)

About

Language - Loop (For, While) - (Break, Continue) in the DOM.

Iterate

Web API

A selection of element with the Web API DOM is returned as a nodelist.

for(var i = 0; i < nodeList.length; i++) {
   console.log(nodeList[i]);
}
Array.from(elements).forEach(function(el) {console.log(el);})

Web API Example Source

  • Select all the <div> element.
var divs = document.querySelectorAll('div');
  • For each div, add a click event in order to change the background color of the div itself
for(var i = 0; i < divs.length; i++) {
  divs[i].onclick = function(e) {
    e.target.style.backgroundColor = 'rgb(' + Math.round(Math.random()*255) + ',' + 
    Math.round(Math.random()*255) + ',' +Math.round(Math.random()*255) + ')';
    e.target.innerHTML='';
  }
}
  • The Stylesheet
div {
        background-color: DarkSeaGreen;
        height: 50px;
        width: 25%;
        float: left;
        text-align: center;
        vertical-align: middle;
        line-height: 50px;
      }
  • The HTML
<div>Click Me</div><div>Click Me</div><div>Click Me</div><div>Click Me</div>
<div>Click Me</div><div>Click Me</div><div>Click Me</div><div>Click Me</div>
<div>Click Me</div><div>Click Me</div><div>Click Me</div><div>Click Me</div>
<div>Click Me</div><div>Click Me</div><div>Click Me</div><div>Click Me</div>
  • The result where you can click on each text :)

JQuery

Explicit Iteration

  • The HTML
<p>Hello</p>
<p>Nico</p>
$( "p" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
  // You can stop the loop from within the callback function by returning false. ie
  // return false;
  // To access a jQuery object instead of the regular DOM element, use $( this ) in place of this
});

Implicit iteration

// The .each() method is unnecessary here:
$( "li" ).each(function() {
  $( this ).addClass( "foo" );
});
 
// Instead, you should rely on implicit iteration:
$( "li" ).addClass( "bar" );

Documentation / Reference





Discover More
DOM - Element

An element is the most common type of node in the DOM. When you want to do something to an element, first you need to select it. A dom element is generally the memory representation of: an HTML element...
DOM - NodeList (Collection)

A nodelist is the result of a selection that returns more than one node (Generally an element) Nodelist: HTMLAllCollection, HTMLFormControlsCollection, HTMLOptionsCollection, interfaces are...



Share this page:
Follow us:
Task Runner