DOM operations with JavaScript

Finding elements by selector

items = document.querySelectorAll('a.class-name')

Returns a NodeList.

element = document.getElementById('the-id')

Returns a Element.

Iterating over elements


Although NodeList is not an Array, it is possible to iterate on it using forEach(). Several older browsers have not implemented this method yet.

// Newer browsers
items.forEach(function(item){ do something with item })

// Old (how old?) browsers, function(item) { do something with item })

Here’s a polyfill for ES5+ browsers from that NodeList.forEach page linked above:

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = function (callback, thisArg) {
        thisArg = thisArg || window;
        for (var i = 0; i < this.length; i++) {
  , this[i], i, this);