'Javascript: How to get only one element by class name?
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.
Solution 1:[1]
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');
Solution 2:[2]
Clarifications :
getElementsByClassName returns a Node List and not an array
You do not need jQuery
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
Solution 3:[3]
You can use jQuery:
$('.className').eq(index)
Or you can use the javascript built-in method:
var elements = document.getElementsByClassName('className');
This returns a nodeList of elements that you can iterate and make what you want.
If you want only one, you can access the elements in the javascript version like this:
elements[index]
Solution 4:[4]
To anyone looking for a one liner
var first = getElementsByClassName('test')[0];
Solution 5:[5]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Zweih |
| Solution 3 | |
| Solution 4 | StefanJM |
| Solution 5 | Felix Eve |
