What is the difference between either of these approaches to finding elements that are within other specified elements?
// Chaining querySelector()
document.querySelector("#firstDiv").querySelector(".active");
document.querySelector("#firstDiv").querySelectorAll("p");
// Using relative elements
document.querySelector("#firstDiv .active");
document.querySelectorAll("#firstDiv p");
Which approach should I be using? Does it matter? If so, why does it matter?
The first approach is error-prone; if #firstDiv matches nothing, the first call to querySelector() will return null and the following method call will fail with a TypeError.
The second approach, as long as you supply a valid selector, will never throw any errors since you're only dealing with a single call on the document object, which is guaranteed to exist. It will only ever return either the element(s) that match(es) the selector, or null otherwise.
Both approaches are equivalent in that calls to querySelector() or querySelectorAll() on an element object are treated as descendant (subtree) queries.
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