• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / CSS / Selecting Elements By Class Name

Selecting Elements By Class Name

Selecting Elements By Class Name

To select elements by a given class name, you use the getElementsByClassName() method:

let elements = document.getElementsByClassName('className');

The getElementsByClassName() method returns a collection of elements whose class name is the CSS class that you pass into the method. The return collection is a NodeList.

HTML

<html>
<head>
  <title>JavaScript getElementsByClassName() example</title>
</head>
<body>
  <div id="container">
    <p class="note">The first note.</p>
    <p class="note">The second note.</p>
  </div>
  <p class="note">The third note.</p>
  <script src="js/app.js"></script>
</body>
</html>

app.js

let elements = document.getElementsByClassName('note');

for (let i = 0; i < elements.length; i++) {
    console.log(elements[i].innerHTML);
}

Output

The first note.
The second note.
The third note.

Source

https://www.javascripttutorial.net/dom/selecting/selecting-elements-by-class-name/

CSS

Related Snippets:

  • Get the default value of a CSS property with JavaScript
  • Replace a Class of an Element
  • Check If an Element contains a Class
  • Get the Parent of an Element

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers