• 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:

  • Toggle a class for an HTML element
  • Retrieve the value of a CSS rule for the specified element
  • Add a Class to an Element
  • Get the Parent of an Element

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us