How to select elements with ids?

Example

Select an element with an id:

let testImage = document.querySelector("#imageElement");
console.log(testImage);

Try it out for yourself by going to the testing page and running the code in the browser console.

Tip: Press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS) to open the chrome console.

The image with the id imageElement is selected
The image with the id imageElement is selected

Breakdown

Selecting elements with ids is very robust because there are typically no duplicate ids on the same webpage.

You can identify the id of an element by looking at the attributes of an element.

<img id="uniqueImage">

This is an image element that has an id attribute with the value uniqueImage assigned to it. This means we can identify this element using an id.

We can select elements with ids using the document querySelector method.

let uniqueImage = document.querySelector("#uniqueImage");

Between the parentheses, we insert a string that tells the method what element we want to select. We start the word with a hashtag to tell the method that we want to select an id.

We assign the selected element to the newly declared uniqueImage variable.

You can console.log this variable to verify that you have selected the right element.

console.log(uniqueImage);

Syntax

document.querySelector("#id");

Write a comment