Live data from Hacker News

GetElementById vs. QuerySelector

blog.wesleyac.com

91–100 of 100 posts

Re: GetElementById vs. QuerySelector

#91
post #47

Earlier quoted context omitted.

I think for CSS the reason is mostly that IDs have very high specificity, so styling you apply there is very hard to override elsewhere in your stylesheet. However, that just means that you will probably generally want to avoid using IDs in your selectors - not to avoid using them altogether, or in JavaScript.

They should have high specificity - and it should be hard to override them with other selectors - because they are specific. They can only select at most one element. Why would you want to override it? Then you'd have cruft (i.e. a bug in waiting) in the obvious place to look in the future.

> They can only select at most one element.

Incorrect. An ID can be repeated on as many elements in a page as you like. It is only convention that makes an id “unique”. I am not suggesting you do it, since here be dragons e.g. I just got a stack trace in the console of jsbin.com on Mobile Safari when I was testing with two elements with the same id — it breaks developer’s assumptions.

Re: GetElementById vs. QuerySelector

#92

Earlier quoted context omitted.

You are misreading the documentation. There's no such distinction as live node vs. static node in that sense. There's only a distinction between a live node list and a static node list. This is a difference between getElementsByClassName("foo") and querySelectorAll(".foo"), but not between getElementById("foo") and querySelector("#foo"). The difference is whether membership changes in the collection are reflected imm…

Glad to hear that Javascript is such a simple language and only experts should use things like C++.

It's not part of javascript, it's part of the DOM API, and yes, that makes a difference. That's like calling C++ bad because you don't like boost, or calling python bad because you don't like django. (I am not saying tho that there isn't plenty to criticize in javascript itself).

The DOM API is not javascript specific. The API surface is defined in terms of WebIDL (Web Interface definition language). While it is most commonly found in browsers and therefore javascript, it is not specific to browsers or javascript. Browsers themselves ship various javascript environments that do not even include the DOM API at all (WebWorkers aka threads, ServiceWorkers, PAC all give you an environment without a DOM). nodejs doesn't come with a DOM (tho there is an implementation available in jsdom). There is nothing really preventing you from looking at the DOM spec and writing your own DOM API implementation for your preferred language. In fact Microsoft and Google used to do that for their in-browser support of vbscript and dart respectively, python ships with xml.dom (implementing an older version of the spec), java ships with org.w3c.dom (implementing an older version of the spec). There is a C# implementation in the AngleSharp library, somebody wrote a go implementation, and so on.

Re: GetElementById vs. QuerySelector

#93

Earlier quoted context omitted.

I wonder why we need all these different collections. Makes the DOM feel hacked together by lots of totally different people not communicating (?) There's probably a reason, though.

That's because it was hacked together by lots of totally different people not communicating. Over a couple of decades, no less.

Exactly. Once upon a time the powers that were figured a live node list would be cool, so they did that. Many moons later, the new powers that were decided that while a live node list looks cool, it contains too much magic pixie dust which may cause allergies in a lot of people (symptoms include frantically screaming at your screen about why this stuff doesn't work like you expect it to work). But they couldn't just change existing stuff or risk breaking the web. But they could avoid it for new stuff, and so they did that.

Re: GetElementById vs. QuerySelector

#94
post #74

Earlier quoted context omitted.

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.

In terms of convenience, there's no meaningful difference between querySelector and getElementById. Given

    
      
        
      
    
we can do any of

    document.querySelector('.example');
    document.querySelector('#example');
    
    document.getElementById('example');
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...

Re: GetElementById vs. QuerySelector

#95
post #8

Earlier quoted context omitted.

That’s incorrect. Maybe you’re thinking of querySelectorAll, which returns a static list , compared to getElementsByTagName and getElementsByClassName, which return live ones?

I wonder why we need all these different collections. Makes the DOM feel hacked together by lots of totally different people not communicating (?) There's probably a reason, though.

For reference: https://xkcd.com/927/

Re: GetElementById vs. QuerySelector

#96
post #27
post #24

Earlier quoted context omitted.

OP is explaining their methodology poorly. The 62ms number is the time it takes to run the call 100,000 times, in a loop, with a string interpolation. And measurement is done by taking the delta of two performance.now() calls, which are known to be precise to only about 1ms for spectre mitigation[0]. FWIW, JS old timers have known querySelector is slower than getElementById since querySelector became a thing. [0] htt…

I know, that's why it's misleading and it should not be considered. A quick reader will think that "using getElementById will save me 32ms", but it'd be off by several orders of magnitude.

That sounds like a pit of success, though. The gain just isn't that significant. IMHO, misleading would be if querySelector was faster under normal circumstances but shown to be slower through bad benchmarking

Re: GetElementById vs. QuerySelector

#98

Earlier quoted context omitted.

Glad to hear that Javascript is such a simple language and only experts should use things like C++.

It's not part of javascript, it's part of the DOM API, and yes, that makes a difference. That's like calling C++ bad because you don't like boost, or calling python bad because you don't like django. (I am not saying tho that there isn't plenty to criticize in javascript itself). The DOM API is not javascript specific. The API surface is defined in terms of WebIDL (Web Interface definition language). While it is most…

So tell me, how would the invalidation work if the API were written in a language like Rust?

You've just listed a bunch of GCed languages and told me it's due to the API not the language. GC lets you be sloppy with resource initialization/cleanup though, and having GC doesn't magically fix when the external objects you interact with go in and out of scope.

So what I'm arguing above is that GCed languages are actually just as hard as manual memory managed languages the moment you need to interact with the real world... be it UI elements, file handles, network sockets, or whatever. Memory isn't the only resource that needs management, and languages that have idiomatic resource management are actually good at this kind of thing.

Re: GetElementById vs. QuerySelector

#99

Earlier quoted context omitted.

Glad to hear that Javascript is such a simple language and only experts should use things like C++.

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

No, it's a language issue. The language doesn't let you specify that things cannot go out of scope 'spookily', so it is ambiguous and you have to trust things like documentation. Just like it's easy to make memory management issues in C, this is the kind of thing that's easy to get wrong in JS.

Re: GetElementById vs. QuerySelector

#100
post #91

Earlier quoted context omitted.

They should have high specificity - and it should be hard to override them with other selectors - because they are specific. They can only select at most one element. Why would you want to override it? Then you'd have cruft (i.e. a bug in waiting) in the obvious place to look in the future.

> They can only select at most one element. Incorrect. An ID can be repeated on as many elements in a page as you like. It is only convention that makes an id “unique”. I am not suggesting you do it, since here be dragons e.g. I just got a stack trace in the console of jsbin.com on Mobile Safari when I was testing with two elements with the same id — it breaks developer’s assumptions.

Incorrect. getElementById returns a single element, regardless of how many elements you put with the same id; furthermore, having multiple elements with the same id is a violation of the relevant standards, so browsers may do whatever they want at that point (including ignore the repeated id on ALL elements, ignoring it on SOME elements, or honoring it on all elements). And in fact various browsers at various times have done all 3 of those things. Even today both Chrome and Firefox do two of those things depending on how you look at it (getElementById returns a single element, but CSS selectors apply to all elements with the ID).

It is only convention that gives anything meaning. HTML attributes are given meaning by convention. The words I'm writing right now are given meaning by convention. That implies abolutely nothing about the meaning or validity thereof.

> the id attribute value must be unique amongst all the IDs in the element's tree ... The id attribute specifies its element's unique identifier (ID).

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

Post reply on HN