DOM - Collection Iteration (NodeList, ..)

> (World Wide) Web - (W3|WWW) > The Document Object Model W3C API Interface (DOM)

1 - About

3 - Iterate

3.1 - Web API

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

  • For
for(var i = 0; i < nodeList.length; i++) {
   console.log(nodeList[i]);
}
  • forEach Property
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 :)

Advertising

3.2 - JQuery

3.2.1 - 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
});

3.2.2 - Implicit iteration

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

4 - Documentation / Reference

web/dom/loop.txt ยท Last modified: 2019/02/09 11:41 by gerardnico