Back to course

Selecting Elements: querySelector() and querySelectorAll()

JavaScript: The Complete '0 to Hero' Beginner Course

80. Selecting Elements: querySelector() and querySelectorAll()

These modern selection methods are far more flexible than getElementById because they use CSS selectors.

1. querySelector()

Returns the first element in the document that matches the specified CSS selector.

Example: Select an ID, Class, or Tag.

javascript // Select the element with ID 'header' const header = document.querySelector('#header');

// Select the first element with class 'item' const firstItem = document.querySelector('.item');

// Select the first tag inside a div const link = document.querySelector('div > a');

2. querySelectorAll()

Returns a static NodeList (like an array) of all elements that match the specified CSS selector.

javascript // Select all elements with the class 'button' const buttons = document.querySelectorAll('.button');

console.log(buttons.length); // How many buttons were found

// We must loop over the NodeList to access each element: buttons.forEach(btn => { btn.style.backgroundColor = 'blue'; });

Best Practice: Prefer querySelector and querySelectorAll for robust and complex selection.