GetElementById vs. QuerySelector

This page summarizes the projects mentioned and recommended in the original post on news.ycombinator.com

Our great sponsors
  • InfluxDB - Power Real-Time Data Analytics at Scale
  • WorkOS - The modern identity platform for B2B SaaS
  • SaaSHub - Software Alternatives and Reviews
  • dom

    DOM Standard

    and get the same result, namely the Element object representing that div.

    When there are multiple matching elements on the page, results differ. From document.querySelector() you get back "the first Element within the document that matches the specified selector, or group of selectors" [1], and the spec defines the search for "first" as depth-first. [2] [3] Meanwhile, the docs for document.getElementById() [4] mention that "element IDs are required to be unique if specified", and this too we find borne out in the relevant spec. [5]

    If there is a specified way for DOM implementations to behave when element IDs aren't unique in the document, I haven't yet been able to find it. In any case, given the liberality with which the docs are peppered with warnings and reminders that IDs must be unique, violating that invariant takes us outside the expectation of implementation guarantees, so it's not all that easy to complain if it behaves differently across browsers or otherwise isn't predictable.

    So, for elements that exist only once, it's as easy to select them by class as by ID, and using a class has the additional benefit that it's one fewer refactor if you do decide to use that element more than once - if you use ID to begin with, you have to change that when you reuse the element. This is also not a meaningful difference in convenience, I think.

    [1] https://developer.mozilla.org/en-US/docs/Web/API/Document/qu...

    [2] https://drafts.csswg.org/selectors-4/#match-a-selector-again...

    [3] https://dom.spec.whatwg.org/#concept-shadow-including-tree-o...

    [4] https://developer.mozilla.org/en-US/docs/Web/API/Document/ge...

    [5] https://html.spec.whatwg.org/multipage/dom.html#global-attri...

  • InfluxDB

    Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.

NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a more popular project.

Suggest a related project

Related posts