Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - How to Manipulate DOM Elements?
Next article icon

How to select DOM Elements in JavaScript ?

Last Updated : 05 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or modifying styles.

Below are the approaches to select DOM elements in JavaScript:

Table of Content

  • Using getElementById
  • Using getElementsByClassName
  • Using getElementsByTagName
  • Using querySelector
  • Using querySelectorAll

Using getElementById

This method selects a single element by its unique ID attribute.

Syntax:

document.getElementById('id')

Example:

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width,                     initial-scale=1.0">     <title>getElementById Example</title> </head>  <body>     <h1 id="gfg">GeeksForGeeks</h1>      <script>         // styling the h1 tag         const element = document.getElementById('gfg');         element.style.color = "green";         element.style.textAlign = "center";         element.style.margin = "30px";         element.style.fontSize = "30px";       </script> </body>  </html> 

Output:

select1
Output

Using getElementsByClassName

This method selects elements based on their class attribute. It returns a collection of elements with the specified class name.

Syntax:

 document.getElementsByClassName('class')

Example:

HTML
<!DOCTYPE html> <html lang="en">    <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>getElementsByClassName Example</title> </head>    <body>     <h1 class="selector">GeeksForGeeks</h1>     <h2 class="selector">DOM selector in JavaScript</h2>      <script>         const elements =          documSizeent.getElementsByClassName('selector');         elements[0].style.color = "green";         elements[1].style.color = "red";         elements[0].style.textAlign = "center";         elements[1].style.textAlign = "center";         elements[0].style.marginTop = "60px";     </script> </body>    </html> 

Output:

select2
Output

Using getElementsByTagName

This method selects elements based on their tag name. It returns a collection of elements with the specified tag name.

Syntax:

document.getElementsByTagName('tag')

Example:

HTML
<!DOCTYPE html> <html lang="en">    <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>getElementsByTagName Example</title> </head>    <body>     <p>Thanks for visiting GFG</p>     <p>This is showing how to select DOM element using tag name</p>      <script>         const paragraphs = document.getElementsByTagName('p');         paragraphs[0].style.color = "green";         paragraphs[1].style.color = "blue";         paragraphs[0].style.fontSize = "25px";         paragraphs[0].style.textAlign = "center";         paragraphs[1].style.textAlign = "center";         paragraphs[0].style.marginTop = "60px";     </script> </body>    </html> 

Output:

select3
Output

Using querySelector

This method selects the first element that matches a specified CSS selector. It returns only one element.

Syntax:

document.querySelector('selector')

Example:

HTML
<!DOCTYPE html> <html lang="en">    <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                    initial-scale=1.0">     <title>querySelector Example</title> </head>    <body>     <div class="gfg">GeeksForGeeks</div>      <script>         const element =          document.querySelector('.gfg');         element.style.color = "green";         element.style.textAlign = "center";         element.style.margin = "30px";         element.style.fontSize = "30px";     </script> </body>    </html> 

Output:

select1
Output

Using querySelectorAll

Similar to querySelector, but it returns a NodeList containing all elements that match the specified CSS selector.

Syntax:

document.querySelectorAll('selector')

Example:

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>querySelectorAll Example</title> </head>  <body>     <h1 class="selector">GeeksForGeeks</h1>     <p class="selector">         This is showing how to select DOM element         using tag name     </p>      <script>         const elements = document.querySelectorAll('.selector');         elements[0].style.color = "green";         elements[1].style.color = "red";         elements[0].style.textAlign = "center";         elements[1].style.textAlign = "center";         elements[0].style.marginTop = "60px";     </script> </body>  </html> 

Output:

select5
Output

Next Article
JavaScript - How to Manipulate DOM Elements?

S

strikeackr
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Select an Element by ID in JavaScript ?
    In JavaScript, we can use the "id" attribute to interact with HTML elements. The "id" attribute in HTML assigns a unique identifier to an element. This uniqueness makes it easy for JavaScript to precisely target and manipulate specific elements on a webpage. Selecting elements by ID helps in dynamic
    2 min read
  • JavaScript - How to Manipulate DOM Elements?
    The DOM stands for the Document Object Model (DOM), which allows us to interact with the document and change its structure, style, and content. We can use the DOM to change the content and style of an HTML element by changing its properties. In this article, we will discuss how to manipulate the DOM
    6 min read
  • How to Create a Select All Checkbox in JavaScript ?
    In web apps with lots of checkboxes, a "Select All" checkbox is useful. It lets users check or uncheck all checkboxes at once, making things quicker. This feature can be implemented in various ways, such as utilizing JavaScript and JQuery to incorporate a "Select All" checkbox. This enhances the app
    2 min read
  • How to select element by ID in jQuery ?
    In this article, we are going to see how to select the element by its id using jQuery. To learn about this topic one should have prior knowledge about HTML, CSS, JavaScript and jQuery. Using JavaScript: This question is also solved by a popular JavaScript method called document.getElementById() whic
    2 min read
  • How to get all ID of the DOM elements with JavaScript ?
    Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below: Approach 1: First select all elements using $('*') selector, which selects every element of the document.Use .each() method to traverse all
    2 min read
  • How To Get Element By Class Name In JavaScript ?
    When working with the DOM in JavaScript, selecting elements by their class names is a common task. JavaScript provides several methods to achieve this, whether we need to select one or multiple elements. In this article, we will cover different approaches to get elements by class name in JavaScript.
    3 min read
  • How to get/change the HTML with DOM element in JavaScript ?
    In order to get/access the HTML for a DOM element in JavaScript, the first step is to identify the element base on its id, name, or its tag name. Then, we can use inner.HTML or outer.HTML to get the HTML. Using the getElementById() method: This method gets/identifies the DOM elements using its ID an
    3 min read
  • Generate CSS Selector for Target Element in JavaScript
    When we are working with web development, applying the styles to the elements dynamically is very common for creating interactive web pages. To apply the styles dynamically to the elements, it is very essential to understand the CSS selectors. What is a CSS Selector?A CSS selector is a pattern used
    3 min read
  • How getElementByID works in JavaScript ?
    The document method getElementById() returns an element object representing the element whose id property matches with the given value. This method is used to manipulate an element on our document & is widely used in web designing to change the value of any particular element or get a particular
    2 min read
  • How to select elements by attribute in jQuery ?
    jQuery is a lightweight JavaScript library. In the vanilla JavaScript language, the getElementById method is used to select an element. However, jQuery provides a much lighter alternative for the same purpose. The 'jQuery Selector' allows the user to manipulate HTML elements and the data inside it(D
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences