Essentials

jQuery function

Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string, or register a callback to call when the DOM is fully loaded.

Get element collection

jQuery

var elements = $('div');

Vanilla JS

var elements = document.queryAll('div');    

All examples are written assuming that the element collections are true arrays. Note that document.querySelectorAll returns NodeList, which is a fake array. Either use document.queryAll everywhere or convert all NodeLists to arrays(Array.from, [].slice.call, ...).

Get element collection in the specific container

jQuery

var elements = $('div', container);

Vanilla JS

var elements = container.queryAll('div');

Create a new element

jQuery

var element = $('<div>');

Vanilla JS

var element = document.createElement('div');

Specify a function to execute when the DOM is fully loaded

jQuery

$(function() {
    // ...
});

Vanilla JS

document.addEventListener('DOMContentLoaded', function() {
    // ...
});

each

Iterate over a jQuery object, executing a function for each matched element.

jQuery

elements.each(function() {
    this.doSomething();
});

Vanilla ES6+

for (var element of elements)
    element.doSomething();

Vanilla ES5

elements.forEach(function(element) {
    element.doSomething();
});

Anywhere - large collections

for (var id = 0; id < elements.length; id++)
    elements[id].doSomething();

Using each, for-of or forEach brings a cleaner code, but at the same time it can have a big impact on overall performance. In the case you are manipulating large DOM collections(tens of thousands of elements and over), you should stick with the plain old for and while loops.

shopify traffic stats