Categories
JavaScript

Node Selectors

Function               | Live? | Type           | Time Complexity
querySelector          |       | Element        |  O(n)
querySelectorAll       |   N   | NodeList       |  O(n)
getElementById         |       | Element        |  O(1)
getElementsByClassName |   Y   | HTMLCollection |  O(1)
getElementsByTagName   |   Y   | HTMLCollection |  O(1)
getElementsByName      |   Y   | NodeList       |  O(1)
  • HTMLCollection
    • The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements in document order and offers methods and properties for selecting from the list.
    • An HTMLCollection is live (getElement* calls return collections of references), it is automatically updated when the underlying document is changed.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

  • HTMLCollections are not as array-like as NodeLists and do not support .forEach().
    Work around:
    [...document.getElementsByClassName("someClass")].forEach()
  • getElementById and getElementByName are exclusively for document
  • Chaining getElement* calls instead of querySelector* will improve performance.
  • document.querySelectorAll(“.class1.class2”) = document.getElementsByClassName(“class1 class2”)

https://stackoverflow.com/a/54819633

Leave a comment