Interactive online courses HTML Academy
2026-03-09 14:10 Diff

Searching for elements on the page:

// Searching for an element by tag var list = document.querySelector('ul'); // Searching for the last element from the list var lastProduct = document.querySelector('li:last-child'); // Searching for an element by class var price = document.querySelector('.price'); // Searching for the third element from the product list var thirdProduct = document.querySelector('.product:nth-child(3)'); // Searching for all elements that match the selector var listItems = document.querySelectorAll('.product');

querySelectorAll returns a list (collection) of elements. This list is similar to an array, but it is not. It’s called a pseudo-array, and you can go through it using a loop.

Add a class to a page element:

// When searching for an element by class, use dot var product = document.querySelector('.product'); // But when we add a class, there is no dot! product.classList.add('product--sale');

The result of classList.add() is the same as when we manually add a class to the layout:

<!-- Initial markup state --> <li class="product"> … </li> <!-- State after calling classList.add --> <li class="product product--sale"> … </li>
Continue