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.

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

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

Attribute Value Substring Matching

Using starts with, ^

const extlinks = document.querySelectorAll('a[href^="https://"]');

Using ends with, $

const element = document.querySelector('[data-cmp-contentfragment-model$="/cf-modal"]');

Using contains, *

const googlelinks = document.querySelectorAll('a[href*="google.com"]');

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('.someclass');

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

Optionally pass an index argument for where to begin iteration. For example, start with index 2 in the nodeList:

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

You can also pass an index for where to stop iteration. For example, end on index 6.

[].slice.call(nodeList, 0, 6).forEach((el, index) => {...});

Scenario - use a map to get all of the option values from a select element skipping the first since its value is empty.

[].slice.call(document.querySelector(select), 1).map(option => option.value);

Resources

comments powered by Disqus