JavaScript

How to select an element using tag with JavaScript

November 8, 2021

How to select an element using tag with JavaScript

In this article we’ll learn the easiest way to select an element using tag in the JavaScript language, one of its DOM manipulation methods

select an element using tag cover

What’s up, programmer, let’s learn something new? 

In the JavaScript language, or JS for intimates, we have several ways to manipulate the elements

And also to select them, either by: class, id or even by their HTML tag, which is the subject of this post

For this we must use a method called getElementsByTagName, in the document

This method will return a set of elements that share the same tag.

See how to use:

// Selecionar by tag

let els = document.getElementsByTagName("tag");

As mentioned before, we use the method in document

And if there is any correspondence, all the tags we request are sent to us in return.

Therefore, as the project grows, this can become a problem and return unnecessary elements

So we can choose other methods, broad and specific, see:

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

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

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

These other methods also allow us to select elements in HTML via DOM

Remembering that if you want to return only one element, you should choose: getElementById and querySelector

If you want multiple elements: getElementsByTagName, getElementsByClassName and querySelectorAll

Conclusion

We saw that to select an element by tag we can use the getElementsByTagName method, it will return all elements with the tag passed by parameter

And that can be a problem as the project grows, so we have other methods that can help us select more specific elements

As an example by element id: getElementById

Want to improve you JS skills? Click here!

Subscribe
Notify of
guest

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