GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • JS Array Object
  • JS Boolean Object
  • JS Date Object
  • JS Math Object
  • JS Number Object
  • JS String Object
  • JS Reserved Keywords
  • More references

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialrepublic.com — JavaScript Selecting DOM Elements - Tutorial Republic

TutorialRepublic
HOME HTML5 CSS3 JAVASCRIPT JQUERY BOOTSTRAP5 v4.6 PHP7 SQL REFERENCES EXAMPLES FAQ SNIPPETS Online HTML Editor
JAVASCRIPT BASIC
JS Introduction JS Getting Started JS Syntax JS Variables JS Generating Output JS Data Types JS Operators JS Events JS Strings JS Numbers JS If…Else JS Switch…Case JS Arrays JS Sorting Arrays JS Loops JS Functions JS Objects
JAVASCRIPT & DOM
JS DOM Nodes JS DOM Selectors JS DOM Styling JS DOM Get Set Attributes JS DOM Manipulation JS DOM Navigation
JAVASCRIPT & BOM
JS Window JS Screen JS Location JS History JS Navigator JS Dialog Boxes JS Timers
JAVASCRIPT ADVANCED
JS Date and Time JS Math Operations JS Type Conversions JS Event Listeners JS Event Propagation JS Borrowing Methods JS Hoisting Behavior JS Closures JS Strict Mode JS JSON Parsing JS Error Handling JS Regular Expressions JS Form Validation JS Cookies JS AJAX Requests JS ES6 Features
JAVASCRIPT EXAMPLES
JS Practice Examples JS FAQ's Answers
JAVASCRIPT REFERENCE
  • JS Properties and Methods
    • JS Array Object
    • JS Boolean Object
    • JS Date Object
    • JS Math Object
    • JS Number Object
    • JS String Object
  • JS Reserved Keywords
  • More references
Advertisements

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

Try this code »
<!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

Try this code »
<!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

Try this code »
<!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 
    let 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

Try this code »
<!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
    let 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(let 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

Try this code »
<!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
    let 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(let 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

Try this code »
<!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
    let 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(let 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.

Previous Page Next Page
Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties
Advertisements

Is this website helpful to you? Please give us a like, or share your feedback to help us improve. Connect with us on Facebook and Twitter for the latest updates.

About Us

Our Story Terms of Use Privacy Policy

Contact

Contact Us Report Error Guest Posts Advertise

Interactive Tools

Bootstrap Icon Search Utility HTML Formatter Title & Meta Length Calculator HTML Color Picker Bootstrap Button Generator SQL Playground Font Awesome Icon Finder HTML Editor

TutorialRepublic

BMC
Copyright © 2026 Tutorial Republic. All Rights Reserved.
Share This:
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.