Selecting Elements with JavaScript
When you want to change something on a webpage with JavaScript like updating text, hiding a section, or adding a new button the first step is selecting the right element.
JavaScript gives us several easy ways to grab elements from the page so we can work with them. Once selected, you can store these elements in variables and reuse them as needed.
There are a few main ways to select elements in JavaScript:
getElementById
One of the most basic ways to select an element is getElementById(). It finds an element by its id attribute.
This is one of the most direct and commonly used methods in JavaScript to grab an HTML element.
Example:
<h1 id="main-title">Hello World</h1>
const title = document.getElementById('main-title');
getElementsByClassName('class')
This selects all elements that share the same class. Since many elements can have the same class, it returns a collection.
Example:
<p class="info">Paragraph 1</p>
<p class="info">Paragraph 2</p>
const infoElements = document.getElementsByClassName('info');
console.log(infoElements.length); // Output: 2
console.log(infoElements[0].textContent); // Output: "Paragraph 1"
Returns an HTMLCollection, which is like an array, but not exactly. You can loop through it using a for
loop or for...of
.
getElementsByTagName('tag')
Want all the <p> tags on the page? This is your method.
Example:
<p>One</p>
<p>Two</p>
<p>Three</p>
const paragraphs = document.getElementsByTagName('p');
console.log(paragraphs.length); // Output: 3
console.log(paragraphs[2].textContent); // Output: "Three"
- You pass in the tag name like
'p'
,'div'
,'button'
, etc. - Returns an HTMLCollection, just like
getElementsByClassName
.
querySelector('selector')
- It’s a bit more flexible because it uses CSS-like selectors.
- It returns the first match.
Example:
<div class="card highlight">Card Content</div>
const highlightedCard = document.querySelector('.card.highlight');
console.log(highlightedCard.textContent); // Output: "Card Content"
Notes
- You can select by class (.class), id (#id), tag (tag), or even more advanced CSS selectors.
- Only returns the first matching element. If there are multiple, the rest are ignored.
querySelectorAll('selector')
This works just like querySelector
, but it returns all matches instead of just the first one.
Example:
<ul>
<li class="item">A</li>
<li class="item">B</li>
</ul>
const items = document.querySelectorAll('.item');
items.forEach(item => console.log(item.textContent)); // Logs "A" then "B"
Notes
- Returns a NodeList, which is similar to an array and supports
forEach()
. - Great when you want to apply changes to multiple elements at once.
Each of these methods gives you a different way to find elements on your page. Stick with getElementById
for fast, single-element grabs, and reach for querySelectorAll
when you want flexibility with CSS-style selectors.