JavaScript

How to select an element using JavaScript

November 7, 2021

How to select an element using JavaScript

In this article we’ll learn how to select an element using JavaScript, all the possible shapes and the use cases for each one.

select an element using JavaScript cover

Hey you  programmer, let’s learn something new?

In JavaScript we have several ways to select an element

This is to cover the many possibilities of elements that HTML can contain, so it becomes very useful

We can select elements by id, class, tag and even by CSS selectors. Isn’t that cool?

First of all, it’s important that these are ways to select are based on methods, that is, functions that JavaScript already gives us by default

Also, all these functions are in the document.

Let’s look at each case:

// Select by id
let el = document.getElementById("id");

// Select by class
let els = document.getElementsByClassName("class");

// Select by tag
let els = document.getElementsByTagName("tag");

// Select by CSS selector
let el = document.querySelector("#id");
let els = document.querySelectorAll(".class");

These are the possibilities we have, and they already cover 100% of the cases

We have some important differences in these methods, which it is interesting to mention

Methods that take only a single element are: getElementById and querySelector

The methods: getElementsByTagName, getElementsByClassName, querySelectorAll  will get all elements that match the input selector

Note elementS and All, both indicate that these methods return sets

And another detail is that in querySelector and querySelectorAll, we use CSS selectors like those in the style sheet, for example:

  • Classes: .class
  • ID: #id
  • Complex selector: .container .item

That is, we must type the # for id and the . to class!

As for the other methods, not only the tag name, class or ID

Conclusion

In JavaScript we have several ways to select elements, so that all cases of HTML elements are selectable

So when we need to select an element by ID, we use the getElementById method

If by class, getElementsByClassName and tags by getElementsByTagName (selectors that select more than one element)

And if we want to select by CSS selectors, we have two possibilities: querySelector (one element) and querySelectorAll (more than one element)

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x