JAVASCRIPT

querySelector

Basic querySelector examples including iteration of DOM NodeList returned by querySelectorAll using either Array.from or [].slice.call.

Element Exists

For example, if a nav element containing a class named someclass exists in the document, do something.

var element = document.querySelector('nav.someclass');

if (element != null) {
    // do something
}

Image Lazy Loader

<img data-src="https://images.unsplash.com/photo-1494633114655-819eb91fde40?auto=format&fit=crop&w=2550&q=80&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D" alt="Above it All. A photo by @anthonyintraversato on Unsplash"/>
const imgList = document.querySelectorAll('img[data-src]');

// lazy load images
Array.from(imgList).forEach(el => {
    el.setAttribute('src', el.getAttribute('data-src'));
    el.onload = function() {
        el.removeAttribute('data-src');
    };
});

Examples of how to iterate through a NodeList object returned by querySelectorAll. The iteration is done on a array object that is created from the DOM NodeList.

Array.from() example

ES6

const nodeList = document.querySelectorAll('myclassname');

Array.from(nodeList).forEach(el => {
    if (el !== null) {
        (async() => {
            await import(`app/module/${el.dataset.component}`);
        })();
    }
});

With index

const nodeList = document.querySelectorAll('myclassname');

Array.from(nodeList).forEach((el, index) => {
    if (el !== null) {
        (async() => {
            await import(`app/module/${el.dataset.component}`);
        })();
    }
});
[].slice.call example

This alternative uses an array object [] to access its prototype slice method.

const nodeList = document.querySelectorAll('myclassname');

[].slice.call(nodeList).forEach((el, index) => {
    if (el !== null) {
        (async() => {
            await import(`app/module/${el.dataset.component}`);
        })();
    }
});

Optionally pass a zero-based index argument for where to begin iteration. for example, index 2 will start with the third item in the nodeList:

[].slice.call(el.filtersList, 2).forEach((input) => {...});

Resources

comments powered by Disqus