Skip to content
landzup edited this page Oct 21, 2019 · 13 revisions

Ever dreamt about playing with the DOM in a jQuery-like style, without having to import the whole library?

Here's what the solution allows: $ is an alias of document.querySelectorAll, as well as other methods are also available on Element and NodeList instances.

Sample HTML document to test DOM basic API:

<div id="main">
</div>

<div id="some">
    <a href="#" class="selected">link</a>
</div>
$div = $('div') // two DIVs found, it is a NodeList instance
$div.length === 2 // true
$div[0] // returns the first DIV

$a = $('a') // one element found, it is an Element instance
$a.length === 1 // true
$a[0] // returns itself

$p = $('p') // no element found, empty NodeList

As either single or multiple matches are indexed and have length property, it is possible iterating over them:

$div.forEach(function(div, i) {
    div.classList.add('selected');
});

$a.forEach(function(a, i) {
   a.classList.remove('selected'); 
});

Attaching events:

// a simple click counter for DIVs:
$('html body > div').on('click', function(e) {
    this.data = this.data || { click: 0 };
    this.data.click++;
    console.log('Clicking ' + e.target.nodeName + ' (' + this.data.click + ')');
});

Clone this wiki locally