JavaScript DOM Selectors

In this tutorial you will learn how to select DOM elements in JavaScript.

Selecting DOM Elements in JavaScript

JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc. But, before you can perform any action you need to find or select the target HTML element.

In the following sections, you will see some of the common ways of selecting the elements on a page and do something with them using the JavaScript.

Selecting the Topmost Elements

The topmost elements in an HTML document are available directly as document properties. For example, the <html> element can be accessed with document.documentElement property, whereas the <head> element can be accessed with document.head property, and the <body> element can be accessed with document.body property. Here’s an example:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Select Topmost Elements</title>
</head>
<body>
    <script>
    // Display lang attribute value of html element
    alert(document.documentElement.getAttribute("lang")); // Outputs: en
    
    // Set background color of body element
    document.body.style.background = "yellow";
    
    // Display tag name of the head element's first child
    alert(document.head.firstElementChild.nodeName); // Outputs: meta
    </script>
</body>
</html>

But, be careful. If document.body is used before the <body> tag (e.g. inside the <head>), it will return null instead of the body element. Because the point at which the script is executed, the <body> tag was not parsed by the browser, so document.body is truly null at that point.

Let’s take a look at the following example to better understand this:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Document.body Demo</title>
    <script>
    alert("From HEAD: " + document.body); // Outputs: null (since <body> is not parsed yet)
    </script>
</head>
<body>
    <script>
    alert("From BODY: " + document.body); // Outputs: HTMLBodyElement
    </script>
</body>
</html>

Selecting Elements by ID

You can select an element based on its unique ID with the getElementById() method. This is the easiest way to find an HTML element in the DOM tree.

The following example selects and highlight an element having the ID attribute id="mark".

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Select Element by ID</title>
</head>
<body>
    <p id="mark">This is a paragraph of text.</p>
    <p>This is another paragraph of text.</p>

    <script>
    // Selecting element with id mark 
    var match = document.getElementById("mark");
     
    // Highlighting element's background
    match.style.background = "yellow";
    </script>
</body>
</html>

The getElementById() method will return the element as an object if the matching element was found, or null if no matching element was found in the document.

Note: Any HTML element can have an id attribute. The value of this attribute must be unique within a page i.e. no two elements in the same page can have the same ID.


Selecting Elements by Class Name

Similarly, you can use the getElementsByClassName() method to select all the elements having specific class names. This method returns an array-like object of all child elements which have all of the given class names. Let’s check out the following example:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Select Elements by Class Name</title>
</head>
<body>
    <p class="test">This is a paragraph of text.</p>
    <div class="block test">This is another paragraph of text.</div>
    <p>This is one more paragraph of text.</p>    

    <script>
    // Selecting elements with class test
    var matches = document.getElementsByClassName("test");
        
    // Displaying the selected elements count
    document.write("Number of selected elements: " + matches.length);
     
    // Applying bold style to first element in selection
    matches[0].style.fontWeight = "bold";
        
    // Applying italic style to last element in selection
    matches[matches.length - 1].style.fontStyle = "italic";
        
    // Highlighting each element's background through loop
    for(var elem in matches) {  
        matches[elem].style.background = "yellow";
    }
    </script>
</body>
</html>

Selecting Elements by Tag Name

You can also select HTML elements by tag name using the getElementsByTagName() method. This method also returns an array-like object of all child elements with the given tag name.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Select Elements by Tag Name</title>
</head>
<body>
    <p>This is a paragraph of text.</p>
    <div class="test">This is another paragraph of text.</div>
    <p>This is one more paragraph of text.</p>   
 
    <script>
    // Selecting all paragraph elements
    var matches = document.getElementsByTagName("p");
        
    // Printing the number of selected paragraphs
    document.write("Number of selected elements: " + matches.length);
     
    // Highlighting each paragraph's background through loop
    for(var elem in matches) {  
        matches[elem].style.background = "yellow";
    }
    </script>
</body>
</html>

Selecting Elements with CSS Selectors

You can use the querySelectorAll() method to select elements that matches the specified CSS selector. CSS selectors provide a very powerful and efficient way of selecting HTML elements in a document. Please check out the CSS tutorial section to learn more about them.

This method returns a list of all the elements that matches the specified selectors. You can examine it just like any array, as shown in the following example:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JS Select Elements with CSS Selectors</title>
</head>
<body>
    <ul>
        <li>Bread</li>
        <li class="tick">Coffee</li>
        <li>Pineapple Cake</li>
    </ul>
        
    <script>
    // Selecting all li elements
    var matches = document.querySelectorAll("ul li");
     
    // Printing the number of selected li elements
    document.write("Number of selected elements: " + matches.length + "<hr>")
     
    // Printing the content of selected li elements
    for(var elem of matches) {  
        document.write(elem.innerHTML + "<br>");
    }
     
    // Applying line through style to first li element with class tick
    matches = document.querySelectorAll("ul li.tick");
    matches[0].style.textDecoration = "line-through";
    </script>
</body>
</html>

Note: The querySelectorAll() method also supports CSS pseudo-classes like :first-child, :last-child, :hover, etc. But, for CSS pseudo-elements such as ::before, ::after, ::first-line, etc. this method always returns an empty list.

© 2024 All rights reserved. | Made With 🤍 By The_MAK Team