Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to get only one element by class name?

Tags:

javascript

How do I get only one DOM element by class name? I am guessing that the syntax of getting elements by class name is getElementsByClassName, but I am not sure how many elements it's going to return.

like image 557
Ismatjon Avatar asked Jan 29 '14 15:01

Ismatjon


People also ask

Can you get element by class in JavaScript?

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.

Can we get element by class?

You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur.

How can I get all of the elements with the same class name in JavaScript?

Using JavaScript – querySelector() function The querySelectorAll() method returns all elements within the document having the same class. To get the first element that matches the specified selector, you can use the querySelector() method.


2 Answers

document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array returned.

var elements = document.getElementsByClassName('className'); var requiredElement = elements[0]; 

Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.

// HTML <div id="myElement"></div>  // JS var requiredElement = document.getElementById('myElement'); 
like image 145
Rahat Khanna Avatar answered Oct 18 '22 16:10

Rahat Khanna


Clarifications :

  1. getElementsByClassName returns a Node List and not an array

  2. You do not need jQuery

  3. What you were looking for was probably document.querySelector :

How do I get only one DOM element by class name?

var firstElementWithClass = document.querySelector('.myclass'); 

Also see: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector

like image 20
sebilasse Avatar answered Oct 18 '22 14:10

sebilasse