JavaScript Searching: getElement*, querySelector*
Exploring and mastering the Document Object Model (DOM) is crucial for JavaScript developers aiming to build interactive and dynamic web applications. This
Learning to search and select elements in the Document Object Model (DOM) is key for JavaScript developers who want to make websites interactive. This guide covers both legacy DOM methods and modern query selectors, and includes simple examples that you can try out.
Efficient Element Access: getElementById
The getElementById method is a fast and reliable way to access a specific element by its unique ID. Because the browser can optimize ID lookups, this method is generally faster than CSS selector methods. In the example below, the initial "Default text" is immediately replaced by the JavaScript code.
<!-- snippet: html-result -->
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<div id="main-content">Default text</div>
<script>
const element = document.getElementById('main-content');
element.innerHTML = "Modified text!"
</script>
</body>
</html>Accessing Multiple Elements: getElementsByClassName and getElementsByTagName
When you select elements by their class name or tag name, you will receive an HTMLCollection. This is a live collection that updates automatically when the DOM changes, and it behaves like an array for accessing elements by index and reading the length property. To iterate over it, you need to first convert it into an array with the Array.from method.
Example Using getElementsByClassName
Access multiple elements with the same class using getElementsByClassName. In this example we have two div elements with the same class name. We modify both of them by selecting those elements by their class name.
<!-- snippet: html-result -->
<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<div class="info">First Info</div>
<div class="info">Second Info</div>
<script>
const infoElements = document.getElementsByClassName('info');
Array.from(infoElements).forEach(el => el.innerHTML = "MODIFIED!");
</script>
</body>
</html>Example Using getElementsByTagName
Retrieve elements by their tag name with getElementsByTagName. It's completely similar to the previous one, but this time we select by the tag name, not the class name.
<!-- snippet: html-result -->
<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<script>
const paragraphs = document.getElementsByTagName('p');
Array.from(paragraphs).forEach(el => el.innerHTML = "MODIFIED!");
</script>
</body>
</html>Flexible Searches with querySelector and querySelectorAll
Selecting with querySelector
Use querySelector to find the first element matching a CSS selector. In this example, we select the first element with the class text that is a direct child of the element with the main id.
<!-- snippet: html-result -->
<!DOCTYPE html>
<html>
<head>
<title>QuerySelector Example</title>
</head>
<body>
<div id="main"><span class="text">This will be replaced</span></div>
<div id="other"><span class="text">This one doesn't change</span></div>
<script>
const spanInsideDiv = document.querySelector('#main > .text');
spanInsideDiv.innerHTML = "MODIFIED!";
</script>
</body>
</html>Retrieving Multiple Elements with querySelectorAll
querySelectorAll allows you to select all elements that match a CSS selector. Note that unlike getElementsBy*, which returns a live HTMLCollection, querySelectorAll returns a static NodeList that captures a snapshot of the elements at the time of selection and does not update automatically when the DOM changes.
<!-- snippet: html-result -->
<!DOCTYPE html>
<html>
<head>
<title>QuerySelectorAll Example</title>
</head>
<body>
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
</ul>
<script>
const items = document.querySelectorAll('.item');
items.forEach(item => item.innerHTML = "MODIFIED!");
</script>
</body>
</html>Conclusion
The techniques outlined in this guide provide JavaScript developers with powerful tools to access and manipulate the DOM efficiently. By incorporating these methods, developers can significantly enhance the interactivity and responsiveness of their web applications. These examples are ready to be tested in an HTML file, offering hands-on experience with each method discussed.
Practice
Which of the following statements are correct about JavaScript's querySelector and getElementById methods?