Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Select element – JavaScript

Summary

To select an element using JavaScript, use the querySelector() method:

const myParagraph = document.querySelector('p');

Details

In order to start working with elements on a web page in your JS code, you have to select the elements first. To select one element on a web page, use the querySelector() method. You can use any valid CSS selector with the querySelector() method. Here is an example of using an id selector:

const elementWithId = document.querySelector('#id-name');

Here is an example of using a class selector:

const elementWithClass = document.querySelector('.class-name');

If you use a selector that applies to multiple elements on the web page, the computer will only return the first element on the web page that matches that selector.

Alternatives

You can also use the getElementById() to find an element with a particular id. Notice that you don’t need the hashtag symbol before the id name, unlike when you use querySelector().

const elementWithId = document.getElementById('id-name');

Exercises

There are no exercises for this lesson.

References

Manipulating documents on MDN (see the section called Moving and removing elements)

querySelector() method on MDN

getElementById() method on MDN

Back to: JavaScript Reference > JS DOM