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]);
}
- forEach Property
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>
- The Jquery Each Function
$( "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" );