How to Find the Right Piece?
Before you can change a button's color or read text from an input field, you first need to find that specific element in the massive DOM tree.
1. querySelector & querySelectorAll
This is the most powerful and modern way to find elements. It uses the exact same syntax you use in CSS to style elements!
querySelector('selector'): Finds the first element that matches the selector.querySelectorAll('selector'): Finds all elements that match the selector and returns them in a list (a NodeList).
Try finding the main heading (H1 tag) of this page! Type the command below:
Type: document.querySelector('h1').textContent
Now let's count how many paragraphs (<p> tags) are on this page:
Type: document.querySelectorAll('p').length
2. Older Methods (Sometimes Faster)
Before querySelector existed, we used these methods. You will still see them very often in older codebases:
getElementById('my-id'): The absolute fastest way to find a single element by its ID.getElementsByClassName('btn'): Returns a collection of all elements with that class.
Methods like getElementsByClassName and getElementsByTagName return a ** " live " collection**. This means if you delete an element from the page using JS, it automatically disappears from your variable too! querySelectorAll, on the other hand, returns a " static snapshot " of the data at the exact moment you called it.