In a piece of example code I wrote
var as = toArray(document.getElementsByClassName("false")).filter(function (el) {
return el.tagName === "A";
});
And I was thinking I could replace that with
var as = document.querySelectorAll("a.false");
Now after reading the following facts
qsa
instead of document.querySelectorAll
because I'm lazy.Question: When should I favour QSA over the normal methods?
It's clear that if your doing qsa("a")
or qsa(".class")
or qsa("#id")
your doing it wrong because there are methods (byTagName, byClassName, byId) that are better.
It's also clear that qsa("div > p.magic")
is a sensible use-case.
Question: But is qsa("tagName.class")
a good use-case of QSA?
As a futher aside there are also these things called NodeIterator
I've asked a question about QSA vs NodeIterator
You should use QSA when the gEBI, gEBN, gEBCN do not work because your selector is complex.
QSA vs DOM parsing is a matter of preference and what your going to be doing with the returned data set.
If browser support was not an issue I would just use it everywhere. Why use 4 different methods (...byId, ...byTagName, ...byClassName) if you could just use one.
QSA seems to be slower (...byId), but still only takes a few miliseconds or less. Most of the times you only call it a few times, so not a problem. When you hit a speed bottleneck you could always replace QSA with the appropriate other one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With