zeckdude
zeckdude

Reputation: 16183

Difference between using relative elements in selector or chaining querySelector?

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?

Upvotes: 2

Views: 2800

Answers (1)

BoltClock
BoltClock

Reputation: 724472

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.

Upvotes: 5

Related Questions