• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • 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
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • 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
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • 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
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • 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
Home >> javascript >> JS DOM Selectors

JS DOM Selectors

Welcome to another tutorial, here you will learn how to select DOM elements in JavaScript.

 

Selecting DOM Elements in JavaScript

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

In subsequent sections in this tutorial, we will learn the common ways of selecting the elements on a page and doing something with them using JavaScript.
 

Selecting the Topmost Elements

In an HTML document, the topmost elements are available directly as document properties. For instance, the ‘html’ element can be accessed with ‘document.documentElement property’, while the ‘head’ element can be accessed with ‘document.head property’, and the ‘body’ element can be accessed with ‘document.body property’. Below is an 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>

Try with example

 

However, 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. This is because, at 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.

Here is an example to better understand this:

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

Try with example


Selecting Elements by ID

In selecting elements by ID, the getElementById() method is used. It is the simplest and easiest way to find an HTML element in the DOM tree.

The example shown below 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>

Try with example

 

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

Note: id attribute is a unique feature of any HTML element. However, the value of this attribute must be unique within a page (i.e no two elements on the same page can have the same ID).

 

Selecting Elements by Class Name

In this case, you can use the getElementsByClassName() method to select any elements having specific class names. The ‘getElementsByClassName()’ method returns an array-like object of any child elements which have all of the given class names. See it in the example below:

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

Try with example


Selecting Elements by Tag Name

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

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

Try with example

 

Selecting Elements with CSS Selectors

In this case, the querySelectorAll() method can also be used to select elements that match the specified CSS selector. The CSS selectors are known to provide a powerful and efficient way of selecting HTML elements in a document. 

You can check out the CSS tutorial section to learn more about their features and how to use them.

This querySelectorAll() method returns a list of all the elements that match the specified selectors. It can be used to examine it just like any array, as shown in the 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>

Try with example

 

Note: The querySelectorAll() method also supports CSS pseudo-classes such as, :first-child, :last-child, :hover, etc. However, for CSS pseudo-elements like, ::before, ::after, ::first-line, and so on. This method when used always returns an empty list.

You can check out the CSS tutorial section to learn more about their features and how to use them.

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.