What’s up, programmer, let’s learn something new?
Watch this content on YouTube:
We can select by id, tags and also classes, which is what we’ll cover in this post
The method for selecting an element by class is getElementsByClassName
It must be called by the document and as we are using one class per selector, it has an important peculiarity
If there are two elements with the same class, the method will bring them both. Isn’t that cool?
So look at the syntax:
// Select by class name let els = document.getElementsByClassName("elementClass");
Note: do not add the ( . ) of the class as it is done in CSS, just its name
If you choose to select only one element, the best options would be by id or query selector, see the syntax:
// Select by id let el = document.getElementById("id"); // Select element by CSS selector let el2 = document.querySelector(".someClass");
These two samples will only bring a single element
Remembering that the querySelector expects a CSS selector, that is, using # for ids and ( . ) for classes
As for getElementById, just the id name in text
We learned that to select one element per class and multiple elements we also use the getElementsByClassName method
If our option is for only one element, it is better to prefer the methods: getElementById or querySelector