Skip to main content

DOM Querying

Before you can manipulate elements, you need to find them. JavaScript provides several methods to query and select elements from the DOM.

Query Selectors

querySelector

Returns the first element that matches a CSS selector:
querySelector accepts any valid CSS selector, making it very flexible for complex queries.

querySelectorAll

Returns a NodeList of all elements that match a CSS selector:

Classic Methods

getElementById

Returns the element with the specified ID:

getElementsByClassName

Returns a live HTMLCollection of elements with the specified class:
getElementsByClassName returns a live HTMLCollection, meaning it automatically updates when elements are added or removed from the DOM.

getElementsByTagName

Returns a live HTMLCollection of elements with the specified tag name:

getElementsByName

Returns a NodeList of elements with the specified name attribute:

Traversing the DOM

Parent Elements

Child Elements

Sibling Elements

Special Selections

Get Focused Element

Get All Inputs in a Form

Get Elements by Attribute

Checking Element Matches

matches()

Check if an element matches a CSS selector:

contains()

Check if an element contains another element:

Performance Tips

Cache Selections

Don’t query the DOM repeatedly for the same element:

Scope Queries

Query within a specific element instead of the entire document:

Use Specific Selectors

Practical Examples

Find All Empty Elements

Find Elements by Text Content

Get Visible Elements Only

querySelector vs getElementById

getElementById is generally faster than querySelector('#id') because it’s optimized for ID lookups. However, the difference is usually negligible.
querySelector is more flexible as it accepts any CSS selector, while getElementById only works with IDs.
Both return a single element or null. getElementById is more specific and only works with IDs.
Use getElementById when you specifically need to find an element by ID. Use querySelector for more complex selections or when you need CSS selector flexibility.

Common Patterns

Store DOM References

Delegate Event Listeners

Best Practices

querySelector and querySelectorAll are more flexible and work consistently across all scenarios.
Store frequently accessed elements in variables to avoid repeated DOM queries.
Query within specific containers rather than the entire document when possible.
Use Array.from() or the spread operator to convert NodeLists/HTMLCollections to arrays for better manipulation.