Publié par Florian Margaine le

Note: This post is a translation of this one. It deserved it.

A tip if you want to set yourself free from jQuery. I showed earlier this tip to loop over DOM elements, but it's kind of ugly:

Array.prototype.forEach.call( document.querySelectorAll( selector ),
    function( el ) {
    el.textContent = Math.random();
});

That's a lot of text. Using a plain for might even be better. I just thought about a solution that a lot of people should like! It probably exists somewhere else, but I haven't seen it :-)

// Magic line!
NodeList.prototype.forEach = Array.prototype.forEach;

document.querySelectorAll( selector ).forEach( function( el ) {
    el.textContent = Math.random();
});

This works on Firefox, Chrome and IE9. I didn't try other browsers, but if it works on IE...

Online demo on jsfiddle.

This opens up new ways to code. For example, the following works to validate that all the input fields are filled in:

<input type="text">
<input type="text">
<input type="text">
<input type="submit" id="submit" value="Check!">
NodeList.prototype.every = Array.prototype.every;

document.getElementById('submit').addEventListener('click', function() {
    // Check whether all the input are selected
    var all = document.querySelectorAll('input').every(function(el) {
        return el.value !== '';
    });

    if (all) {
        console.log('All checked!');
    }
    else {
        console.log('Some are not checked.');
    }
}, false);

Online demo.

Imagine! What new way could you find?

blog comments powered by Disqus