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:
How to Get Value by Class Name using JavaScript ?
Next article icon

How To Get Element By Class Name In JavaScript ?

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Prerequisites

  • HTML
  • CSS
  • JavaScript

Below are the following approaches to get elements by class name in Javascript:

Table of Content

  • Using document.getElementsByClassName()
  • Using document.querySelector()
  • Using document.querySelectorAll()

1. Using document.getElementsByClassName()

In this approach we are using the document.getElementsByClassName() method. This method selects all elements with a specific class name and returns a live HTMLCollection. Think of it as a way to collect all elements with same label. In this, list gets updated automatically if elements are added or removed.

Syntax:

var elements = document.getElementsByClassName("className");

Example: In this example we are using the getElementsByClassName() method to get element by class name in javascript.

JavaScript
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"      content="width=device-width,       initial-scale=1.0">     <title>Get Elements by Class Name</title>     <style>         .output {             margin-top: 20px;             padding: 10px;             border: 1px solid #ccc;             background-color: #f9f9f9;         }     </style> </head>  <body>     <div class="box">Box 1</div>     <div class="box">Box 2</div>     <div class="box">Box 3</div>      <div class="output" id="output1"></div>      <script>         var boxes =          document.getElementsByClassName("box");         var output =          document.getElementById("output1");         output.innerHTML =          "Number of boxes: " + boxes.length;     </script> </body>  </html> 


Output:

file
Output Using document.getElementbyClassName

2. Using document.querySelector()

In this approach we are using the document.querySelector() method. This method returns the first element that matches the specified selector (class name). It is useful when you only need to select a single element by class name.

Syntax:

var element = document.querySelector(".className");

Example: In this example we are using the querySelector() method to get element by class name and we will change the background color of selected class in javascript.

JavaScript
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"      content="width=device-width,'' initial-scale=1.0">     <title>Query Selector Example</title>     <style>         .box {             padding: 10px;             margin: 5px;             border: 1px solid #ccc;         }     </style> </head>  <body>     <div class="box">Box 1</div>     <div class="box">Box 2</div>     <div class="box">Box 3</div>      <script>         var firstBox =          document.querySelector(".box");         firstBox.style.backgroundColor =          "lightblue"; // Change the background color to light blue         firstBox.style.color = "white"; // Change the text color to white     </script> </body>  </html> 


Output:

file
Output using document.querySelector

3. Using document.querySelectorAll()

In this approach we are using the document.querySelectorAll() method. This method finds all elements that match a specific CSS selector, like class name. It gives you a static list, which means it wont automatically update if page changes.

Syntax:

var elements = document.querySelectorAll(".className");

Example: In below example we are using the querySelectorAll and we will print all the content which have that class name.

JavaScript
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"      content="width=device-width,       initial-scale=1.0">     <title>Query Selector All Example</title>     <style>         .output {             margin-top: 20px;             padding: 10px;             border: 1px solid #ccc;             background-color: #f9f9f9;         }     </style> </head>  <body>     <div class="box">Box 1</div>     <div class="box">Box 2</div>     <div class="box">Box 3</div>      <div class="output" id="output3"></div>      <script>         var allBoxes =          document.querySelectorAll(".box");         var output =          document.getElementById("output3");         var content = "Contents of all boxes: <br>";         allBoxes.forEach(function (box) {             content += box.innerText + "<br>";         });         output.innerHTML = content;     </script> </body>  </html> 


Output:

file
Output using document.queryselectorAll

Next Article
How to Get Value by Class Name using JavaScript ?
author
yuvrajghule281
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to Get Cookie by Name in JavaScript?
    Getting a specific name in JavaScript involves parsing the document's cookie string contains all cookies in a single string separated by semicolons and space. The goal is to extract the value of a specific cookie by the name given. The Cookie is defined as a small piece of data that is stored on the
    4 min read
  • How to Toggle an Element Class in JavaScript ?
    In JavaScript, toggling an element class refers to the process of dynamically adding or removing a CSS class from an HTML element. This allows developers to easily change an element's appearance or behavior in response to user actions, such as clicks or events. These are the following methods for to
    2 min read
  • How to Add a Class to DOM Element in JavaScript?
    Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.
    2 min read
  • How to Get Value by Class Name using JavaScript ?
    This article will show you how to use JavaScript to get value by class name. To get the value of an element by its class name in JavaScript, you can use the getElementsByClassName() method. This method returns an array-like object of all elements with the specified class name. You can then access th
    2 min read
  • How to Hide an HTML Element by Class using JavaScript?
    To hide an HTML element by class using JavaScript, the CSS display property can be manipulated. Below are the approaches to hide an HTML element by class: Table of Content Using getElementsByClassName() selectorUsing querySelectorAll() selectorApproach 1: Using getElementsByClassName() selectorIn th
    3 min read
  • How to Filter a DIV Element Based on its Class Name using JavaScript?
    Div Element can be filtered based on class name for displaying specific content using JavaScript. Here, we will explore two different approaches to filtering a DIV element. Table of Content Using querySelectorAll and classListUsing getElementsByClassNameUsing querySelectorAll and classListIn this ap
    3 min read
  • How to get the Class Name of an Object in JavaScript
    In this article, we will learn how we can get the class Name of an Object with multiple approaches in JavaScript. In JavaScript, determining an object's class name can be done using multiple approaches. The constructor property of an object reveals the function that created it, while the instanceof
    3 min read
  • JavaScript adding a class name to the element
    In JavaScript, adding a class name to an element allows you to style or manipulate it via CSS or JavaScript. This can be achieved using different methods. Here, we'll explore two common approaches: using the .className property and the .add() method. Below are the different approaches that could be
    3 min read
  • 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
  • How to select DOM Elements in JavaScript ?
    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 mo
    3 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