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: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 All External Links
Find Elements by Text Content
Get Visible Elements Only
querySelector vs getElementById
Performance
Performance
getElementById is generally faster than querySelector('#id') because it’s optimized for ID lookups. However, the difference is usually negligible.Flexibility
Flexibility
querySelector is more flexible as it accepts any CSS selector, while getElementById only works with IDs.Return type
Return type
Both return a single element or null.
getElementById is more specific and only works with IDs.When to use which
When to use which
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
Use querySelector for modern code
Use querySelector for modern code
querySelector and querySelectorAll are more flexible and work consistently across all scenarios.Cache DOM references
Cache DOM references
Store frequently accessed elements in variables to avoid repeated DOM queries.
Scope your queries
Scope your queries
Query within specific containers rather than the entire document when possible.
Convert NodeLists to Arrays
Convert NodeLists to Arrays
Use
Array.from() or the spread operator to convert NodeLists/HTMLCollections to arrays for better manipulation.