Hey you programmer, let’s learn something new?
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?
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
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)