Selecting descendants or sibling elements? Selecting based on tag and class? Selecting elements with a given attribute present or matching a particular value? Selecting elements with classes starting or ending with a given string? Selecting elements without children? Selecting elements that aren't any of the above.
The question should be the other way around: Why is there `getElementsByClassName` when you can do `querySelectorAll('.myClass')`? Why have `getElementById` when we have `querySelectorAll('#myId')`? Why have `getElementsByTagName` when we have `querySelectorAll('tagName')`?
Apart from the historical reasons both `getElementsByClassName` and especially `getElementById` are optimised - the latter being a simple lookup - which I'm not sure `querySelectorAll` is able to take advantage of.
You’d pay the cost of parsing every time, but otherwise I’d expect SelectorAll to directly depend on getElementBy.. as relevant
Re:I loved jQuery, and still do (2019)
by faitswulff on Tuesday June 29, 2021 @03:33PM
(#27680686)
I use it all the time for bookmarklets and userscripts when I want to customize a page that I can't modify directly. Vendor site showing too many out of stock items? querySelectorAll('div.out-of-stock') and wipe them all out. Filter options not good enough? querySelectorAll('div.price').forEach( /* delete products between x and y prices */ ).
class, id, and tag name are only a small subset of the things you can get with a css query, and you can't combine them with anything when you use the dedicated querySelector methods.
document.querySelectorAll("[data-my-attr=something]")
document.querySelectorAll(".foo > [data-my-attr=something]")
etc.
getElementsByClassName and getElementsByTagName return live HTMLCollection objects that update when the DOM changes (or rather get re-computed when you access their contents following a DOM change). Depending on what you do with them, you may end up with worse performance compared to the NodeLists returned by querySelectorAll.
It’s slower but, assuming you have control over page content, I’d think the answer is probably pseudo selectors or sibling selectors. The more complex stuff really.
Of course if that’s a need the page needs work but, not everything is “fixable” in time limited business cases.
I'm curious as to whether there's a proper use case for querySelectorAll. I always use the getElementsByClassName, getElementById, and getElementsByTagName based on what I want. I find the more general querySelectorAll to be too likely to produce a bug when someone uses a CSS class name that equals a tag or ID. You can make it work, but I find it's too easy to re-use a word in different context, especially if it's different people doing the coding vs CSS.