JavaScript: Selecting Elements By ID, Class, and Tags
This article is a complementary resource to the JavaScript in Browser course.
This article is a complementary resource to the JavaScript in Browser course.
JavaScript: Selecting Elements By ID, Class, and Tags
In JavaScript, querySelector() and querySelectorAll() are powerful, convenient, and preferred methods for selecting elements in your webpage.
However, JavaScript also provides older, more traditional methods like:
getElementById()getElementsByClassName()getElementsByTagName()In this article, you'll learn about these older selection methods in JavaScript with the help of examples.
The getElementById() method selects an HTML element using its unique id. Its syntax is:
document.getElementById("id");
Example
Suppose you have an HTML element with the id title. Then, this is how you select it:
document.getElementById("title")
The equivalent code using querySelector() is:
document.querySelector("#title")
Despite all these advantages, querySelector() is still the better option.
querySelector() method is more flexible (can select by id, class, or tag) while still selecting a single element.The getElementsByClassName() method selects all elements with a given class and returns an HTMLCollection object (a live list of elements). Its syntax is:
document.getElementsByClassName("className")
Note: A live object is one that is automatically updated when the underlying document (webpage) is changed.
Example
Suppose you want to select elements with the class box. Then, you can select them with the following code:
document.getElementsByClassName("box")
The equivalent code using querySelectorAll() is:
document.querySelectorAll(".box")
querySelectorAll() for large lists of elements.getElementsByClassName() returns a live collection, which behaves unpredictably. By contrast, querySelectorAll() returns...querySelectorAll() supports advanced CSS selectors (like .box > p). getElementsByClassName() requires for loops instead of the modern forEach() method.querySelectorAll() is more modern, flexible, and easier to use.The getElementsByTagName() method selects all elements of a given tag name (e.g., <p>, <div>, <button>). Its syntax is:
document.getElementsByTagName("tag")
Example
Suppose you want to select all paragraph elements (<p>). This is how you do it:
document.getElementsByTagName("p")
The equivalent code using querySelectorAll() is:
document.querySelectorAll("p")
querySelectorAll() for large numbers of elements.form elements (<input>, <button>, etc.).querySelectorAll() is more precise, with full CSS selector support.getElementsByTagName() returns a live collection, which can cause issues.getElementsByTagName() has no filtering support. For example, the code document.getElementsByTagName("p.special") won't work.