Learn how to find and select HTML elements using modern querySelector methods.
1. Select by ID
// Select element with id="uniqueId"
const element = document.querySelector('#uniqueId');
This is a unique element with id="uniqueId"
Result: Click to see!
2. Select by Class
// Select all elements with class="special"
const elements = document.querySelectorAll('.special');
Special Item 1
Normal Item
Special Item 2
Result: Click to see!
3. Select by Tag
// Select all paragraph elements
const paragraphs = document.querySelectorAll('p');
First paragraph
This is a div
Second paragraph
Third paragraph
Result: Click to see!
4. Complex Selectors
// Select specific nested elements
const nested = document.querySelector('.parent .child');
Parent box
Child 1
Child 2
Result: Click to see!
Selector Methods and Syntax
Basic Selectors
// Select by ID
const element = document.querySelector('#myId');
// Select by Class
const elements = document.querySelectorAll('.myClass');
// Select by Tag
const divs = document.querySelectorAll('div');
// Select by Attribute
const input = document.querySelector('[type="text"]');