Live data from Hacker News

GetElementById vs. QuerySelector

blog.wesleyac.com

81–90 of 100 posts

Re: GetElementById vs. QuerySelector

#81
post #61

Related: one of my favourite code golfing tricks is named access on the Window object https://html.spec.whatwg.org/multipage/window-object.html#na... >: document.getElementById("result").textContent = "Why do it this way—"; document.querySelector("result").textContent = "—or even this way—"; result.textContent = "—when you can do it this way?"; Edit: adding another similar test to this page, window[`test${i}`] is tak…

Love this trick. It should be noted that the element is added to the window object as long as the id follows the syntax of a valid javascript variable (meaning no dashes).

False on two counts:

1. It doesn’t need to be a valid JavaScript identifier, though if it isn’t you’ll need to use subscripting syntax to access it:

  > document.body.id = "like-this";
  > window["like-this"]
  
2. It’s not added to the window object; rather, property lookup on a window object falls back to looking up elements by ID if there is no such property:

  > typeof example
  "undefined"
  > document.body.id = "example";
  > example
  
  > example = "no longer an element";
  > example
  "no longer an element"
  > delete example;
  true
  > example
  

Re: GetElementById vs. QuerySelector

#82

I'm getting getElementById is 2x to 4x faster than querySelector depending on the browser https://jsbenchit.org/?src=25e097f939f76b559b2515430fb5e459 I'm a little surprised. Sure i'd expected getElementById to be faster but honestly I'd have expected browser implementation of querySelector to do a relatively trivial up front check, is the selector a simple id, if so, call getElementById. I suppose that adds overheads…

Browsers do exactly the optimization you're describing: https://source.chromium.org/chromium/chromium/src/+/main:thi...

Both getElementById and querySelector are quite fast, down to the level of measuring individual branches in a micro benchmark. querySelector does have to do a bit more work to lookup the cached query and a handful of extra branches over getElementById, it's not scanning the document for an ID query unless you're in quirks mode though.

Re: GetElementById vs. QuerySelector

#83
post #41

Earlier quoted context omitted.

> How often do you need to select unique elements by ID? Don't use IDs in the first place. wait a minute, does everyone NOT use IDs for unique elements on page (not each element)? I mean I am genuinely interested in knowing why not to use IDs. There are unique elements which need to be selected on a page like #logout or something.

I use id on unique elements on a page all the time. It can be a form, it can be a button and so on.

That is exactly how use it too. For unique items which 100% will be once on a given page. CSS can be applied too however re-usability of css styles for a given component no more is possible but that is an agreed upon side effect.

Re: GetElementById vs. QuerySelector

#84
post #74
post #41

Earlier quoted context omitted.

I use id on unique elements on a page all the time. It can be a form, it can be a button and so on.

Yeah but they’re not necessary for selection. Label elements actually need an input with ID to function. The other useful use for IDs is for deep-links in articles. But then again that doesn’t mean the id should be used for selection (in JS nor CSS) as it’s probably easier to target many elements with a class, should they ever co-exist. This is basically what you end up with if you build components anyway (even witho…

> Yeah but they’re not necessary for selection

wouldn't it be easier to select an item with ID than select one with a class name and then iterate over to find which one you want. I am talking about items which exist only once. I am still not clear on why not to use IDs in a page in your opinion.

Re: GetElementById vs. QuerySelector

#85

Earlier quoted context omitted.

This is an API issue (DOM), not a language one.

Deflecting to semantics or categorization isn't a defense.

My point it that it is a defined behaviour of the DOM API which is generally implemented in C++ and exposed to Javascript environment. It behave exactly the same way if you use bindings for any other language. It's not an ECMAScript defined feature.

You can also implement exactly this behaviour in any language so how is this then a Javascript language issue?

Re: GetElementById vs. QuerySelector

#86
This is not measuring what the author thinks it's measuring in Chrome. The benchmark iterates through 100,000 sequential IDs, and does so 105 times.

For getElementById:

This is a map lookup every time.

For querySelector:

Chrome caches the parsed selector, but the benchmark doesn't use the same ID twice in any run, so the cache is not effective within a given run. Chrome also has a 256 query limit (per document) on the cache [1] which means that even though the benchmark runs 105 times, each time the browser is parsing 100,000 selectors since the cache would have the last 256 but it always starts at 0. querySelector does have a fast path [2] that calls getElementById which the benchmark hits, but the parsing cost is dominating.

So the benchmark is really measuring selector parsing vs a map lookup. Firefox might have a separate fast path for ID looking selectors that skips the real css parser. It might also have a larger cache.

Chrome's cache should probably be bigger than 256 for modern web apps , but even so that wouldn't help a benchmark that's parsing 100k selectors repeatedly since it doesn't make sense to have a cache that size just for micro benchmarks and real apps don't use 100k unique queries.

[1] https://source.chromium.org/chromium/chromium/src/+/main:thi...

[2] https://source.chromium.org/chromium/chromium/src/+/main:thi...

Re: GetElementById vs. QuerySelector

#87

Why is Chrome so slow with this? Does anyone know

Yes, I explained this above: https://news.ycombinator.com/item?id=29350612

This is less of an issue of Chrome being slow and more about measuring different things across the two browsers because of how the micro benchmark is structured.

Re: GetElementById vs. QuerySelector

#88
post #32
post #15

Earlier quoted context omitted.

The responses to this are a fantastic example of Cunningham’s Law at work. Thank you!

Yeah, I surprised to even see those two terms on an article on HN (who uses getElementById or querySelectors nowadays right?) but I was even more surprised by the number of comments it gathered (which are of course unrelated to the original article)

What else would you use?

Re: GetElementById vs. QuerySelector

#89
post #50

Earlier quoted context omitted.

Woah, no way. Although I could see this being abused, it's amazing that this even works.

It has been abused to allow remote code execution in LastPass, a password manager. https://bugs.chromium.org/p/project-zero/issues/detail?id=12...

You could also crash Internet Explorer 6 simply by including an element with id="tags" on the page. When the user chose to print the page out, the browser would try to access window.tags, find the element instead of what it was expecting to find, and give up.

Re: GetElementById vs. QuerySelector

#90

Earlier quoted context omitted.

> How often do you need to select unique elements by ID? Don't use IDs in the first place. wait a minute, does everyone NOT use IDs for unique elements on page (not each element)? I mean I am genuinely interested in knowing why not to use IDs. There are unique elements which need to be selected on a page like #logout or something.

It’s a common CSS wisdom to use ids very sparingly because there’s always a chance you may want to have the same element on the page multiple times. There are some scenarios in which this is the case you may not expect right away, sometimes you need to duplicate elements for responsivity, for example.

It is uncommon knowledge that id’s do not have to be unique.

document.querySelectorAll('#test').length will return 2 if there are two elements on the page with the same id=test attribute. I personally avoid using that ‘feature’ because it would confuse many people, but it is important to know if you run into certain bugs in code.

Post reply on HN