Part of Series: Javascript Handbook
Javascript

How to select HTML elements in Javascript

📣 Sponsor

In Javascript, it is possible to select an HTML element through your code. That let's us interact directly with specific elements, and change things about them.

Why would we select HTML elements?

There are a number of reasons we would want to target a specific HTML element. It might be to add an event to it - so we can do soemthing when a user clicks on a button, for example. Another reason, might be to programatically change the CSS of an element. For whatever reason we do it, there are a number of functions we have at our disposal to do this in Javascript.

How to select all matching elements in Javascript

We can find specific elements in Javascript using the same selectors we use in CSS. To select all elements with a specific selector, we can use querySelectorAll. For example, if we want to target all divs, we could write the following:

let allDivs = document.querySelectorAll('div');

Now we can target every div and do something to it. When we target multiple HTML elements like this, it returns a NodeList. We can typically iterate over each of these elements using forEach, however not all browsers have impelemented this. You can read more about that here.

let allDivs = document.querySelectorAll('div'); allDivs.forEach(function(item) { // the variable 'item' is each of our divs. // So we can change it. The code below will make all divs have red text! item.style.color = 'red'; });

Selecting the first matching element only

Similar to querySelectorAll, we can use querySelector to select only the first matching element. That means we don't have to loop over our results with forEach:

// The below only targets the first div it finds. let oneDivOnly = document.querySelector('div');

Selecting Elements By ID

We can also select elements by their ID. The reason we might use this is because it is much faster to select something by its ID, rather than searching the document based on a query selector. For example, suppose we've given an HTML element an ID called 'my-id'. We can select it using getElementById:

<div id="my-id"></div>
let myId = document.getElementById('my-id');

Waiting for the document to load

We sometimes run our Javascript before our HTML loads. This may happen if you have your Javascript in the head of your document. If your Javascript is at the bottom of your page, you probably don't need to worry.

If your Javascript is at the top of your page, however, you will want to wait until the document has loaded. If you don't, the HTML will not have loaded yet, so the Javascript file won't be able to select HTML elements - which will throw an error. We can do that using Event Listeners, and waiting for the DOM content to load. The code for that looks like this:

// Using the below line, we can wait for the HTML to load in the page document.addEventListener('DOMContentLoaded', function() { // Everything inside this function, will run after the HTML document has loaded let allDivs = document.querySelectorAll('div'); allDivs.forEach(function(item) { // the variable 'item' is each of our divs. // So we can change it. The code below will make all divs have red text! item.style.color = 'red'; }); })

Selecting Elements by Class

For most use cases, querySelector and getElementById will cover most needs. For some situations, you may prefer to use getElementsByClassName. The problem with getElementsByClassName is that it returns a HTMLCollection, which we cannot use forEach on. As such, we have to use a little bit of Javascript array trickery to do something with each matching elements.

For example, the below will select each element with the class active and set its color to red:

var allActive = document.getElementsByClassName('active'); Array.prototype.filter.call(allActive, function(item) { item.style.color = 'red'; });
Last Updated 1625495805570

More Tips and Tricks for Javascript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email