Add

How to use JavaScript to get elements by class name?

 In this short tutorial, we use JavaScript to get element by class name. We break down the concept, explain the code and then discuss the limitations of the method used.

        Learn Javascript

This tutorial is a part of our initiative at Flexible, to write short curated tutorials around often used or interesting concepts.

Table of Contents - Javascript get element by class:

  • How does the class attribute work?
  • Using the JavaScript getElementByClassName() method
  • Limitation & Caveats - JavaScript get element by class

How does the class attribute work?

The class attribute is an optional property of an HTML element. This attribute can be used on any HTML element. Once a class is created their name can be used by CSS or JavaScript to apply a particular style or to perform certain tasks. This ensures that all the elements belonging to a particular class behave and appear in a similar fashion.
The below code is an example of a class attribute.

<h2 class="classname">Title</h2>

Using the JavaScript getElementByClassName() method:

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.

The syntax is as follows:

var elements = document.getElementsByClassName(name);

Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.

Code and Explanation:

Let’s take a sample HTML code:

<header>
<nav>
<ul id="freelancer">
<li class="item">Name</li>
<li class="item">Skills</li>
<li class="item price">Cost</li>
<li class="item">Projects</li>
</ul>
</nav>
</header>

Now since we intend to look for the element in a particular section we first identify the section along with the ID.

let docs = document.getElementByID('#freelancer');
let elements = freelancer.getElementsByClassName('item');

Now ‘elements’ contain the list of elements with the class name ‘item’.

Limitation & Caveats - JavaScript get element by class:

When using the aforementioned method, note that
If you are trying to get elements with the different class names their names must be separated by whitespace and not a comma.
Class selectors cannot be used in this method.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.