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.
getElementById
One of the most basic ways to select an element is getElementById()
. It finds an element by its id
attribute.
Example:
const title = document.getElementById('main-title');
querySelector
Another popular method is querySelector()
. It’s a bit more flexible because it uses CSS-like selectors:
const firstButton = document.querySelector('.btn');
If you want all buttons with a class .btn
, you can use querySelectorAll()
:
const allButtons = document.querySelectorAll('.btn');
Selecting multiple elements
Sometimes you need to select several elements at once, like a list of all paragraphs or all images. querySelectorAll()
returns a NodeList — a special list of elements you can loop through.
Example:
const paragraphs = document.querySelectorAll('p');
paragraphs.forEach(paragraph => {
paragraph.style.color = 'blue';
});
You can also use methods like getElementsByClassName()
or getElementsByTagName()
, but querySelectorAll()
is generally more modern and flexible.
Storing elements in variables
After selecting an element (or elements), it's a good idea to store them in variables. This way, you don’t have to search the DOM again every time you want to use them.
Example:
const heading = document.querySelector('h1');
heading.textContent = 'Updated Heading';
Storing elements also helps your code run faster and keeps it clean and easy to understand.