by rudian · 5y ago · 0 comments
querySelector *does not* take 62ms to run. Both of them take 0.01ms at most, try it yourself. This is the sort of micro optimization you should not concern yourself with.
How often do you need to select unique elements by ID? Don't use IDs in the first place.
This is akin to using `i--` in loops to "speed up your code" — we're past that.
FWIW, JS old timers have known querySelector is slower than getElementById since querySelector became a thing.
[0] https://developer.mozilla.org/en-US/docs/Web/API/Performance...
> ids.map(id=> `#test${id}`).join(" , ")
or
> `[id^="test"]`
to get all elements that have an id that starts with test
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.
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.
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.
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.
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 without specific frameworks)
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.
Not as an app dev, but if you transpile your code anyway, a transpiler plugin that does this and similar optimizations could be neat.