Modern Selectors
Modern Selectors
Section titled “Modern Selectors”Introduction
Section titled “Introduction”querySelector() and querySelectorAll() use CSS selector syntax, providing powerful and flexible element selection.
Single Element
Section titled “Single Element”// Returns first match or nulldocument.querySelector('#main'); // By IDdocument.querySelector('.article'); // By classdocument.querySelector('div'); // By tagdocument.querySelector('[data-type="post"]'); // By attributedocument.querySelector('div.container > p'); // CSS selectorMultiple Elements
Section titled “Multiple Elements”// Returns a static NodeList (not live)document.querySelectorAll('p'); // All paragraphsdocument.querySelectorAll('.item'); // All .item elementsdocument.querySelectorAll('li:nth-child(2)'); // CSS pseudo-classdocument.querySelectorAll('ul > li'); // Direct childrenVisual Explanation
Section titled “Visual Explanation”flowchart TD A["DOM Selectors"] A --> B["Single Element"] A --> C["Multiple Elements"]
B --> B1["querySelector() ★"] B --> B2["getElementById()"]
C --> C1["querySelectorAll() ★"] C --> C2["getElementsByClassName()"] C --> C3["getElementsByTagName()"]Summary
Section titled “Summary”querySelector()— single element, returns first matchquerySelectorAll()— static NodeList of all matches- Use full CSS selector syntax
- Prefer modern selectors over classic ones