querySelectorAll()
// Using Array.from()
Array.from(myElements).forEach(doSomethingWithEachElement)
// Or prior to ES6
Array.prototype.forEach.call(myElements, doSomethingWithEachElement)
// Shorthand:
[].forEach.call(myElements, doSomethingWithEachElement)
Each element also has a couple of rather self-explanatory read-only properties referencing the “family”, all of which are live:
myElement.children
myElement.firstElementChild
myElement.lastElementChild
myElement.previousElementSibling
myElement.nextElementSibling
As theElementinterface inherits from theNodeinterface, the following properties are also available:
myElement.childNodes
myElement.firstChild
myElement.lastChild
myElement.previousSibling
myElement.nextSibling
myElement.parentNode
myElement.parentElement
Where the former only reference elements, the latter (except for.parentElement) can be any kind of node, e.g. text nodes. We can then check thetypeof a given node like e.g.
myElement.firstChild.nodeType === 3
// this would be a text node
As with any object, we can check a node’s prototype chain using theinstanceofoperator:
myElement.firstChild.nodeType instanceof Text