JavaScript Searching: getElement*, querySelector*

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 focuses on query selectors and includes simple examples that you can try out.

Introduction to DOM Manipulation

The DOM provides a structured representation of the document as nodes and objects, enabling programming languages like JavaScript to interact dynamically with the content, structure, and style of a document.

Efficient Element Access: getElementById

The getElementById method is a fast and reliable way to access a specific element by its unique ID. In the example below, you won't see the "Default text" as it is manipulated by the JavaScript code.

<!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>
Result

Accessing Multiple Elements: getElementsByClassName and getElementsByTagName

When you select elements by their class name or tag name, you will receive a HTML Collection; which is like an array as you can access elements by integer indices and you can read the length property to get the size. But if you want to iterate over the collection, 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.

<!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>
Result

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.

<!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>
Result

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 main id and text class name.

<!DOCTYPE html>
<html>
<head>
    <title>QuerySelector Example</title>
</head>
<body>
    <div id="main"><span class="text">This will be replaced</span></div>
    <div id="main"><span class="text">This one doesn't change</span></div>
    <script>
        const spanInsideDiv = document.querySelector('#main > .text');
        spanInsideDiv.innerHTML = "MODIFIED!";
    </script>
</body>
</html>
Result

Retrieving Multiple Elements with QuerySelectorAll

querySelectorAll allows you to select all elements that match a CSS selector.

<!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>
Result

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 Your Knowledge

Which of the following statements are correct about JavaScript's querySelector and getElementById methods?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?