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

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Solution 3 - Javascript

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 - Javascript

To anyone looking for a one liner

var first = getElementsByClassName('test')[0];

Solution 5 - Javascript

Use NodeList.item().

For example:

var first = getElementsByClassName('test').item(0);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIsmatjonView Question on Stackoverflow
Solution 1 - JavascriptRahat KhannaView Answer on Stackoverflow
Solution 2 - JavascriptsebilasseView Answer on Stackoverflow
Solution 3 - JavascriptLucas ReisView Answer on Stackoverflow
Solution 4 - JavascriptStefanJMView Answer on Stackoverflow
Solution 5 - JavascriptFelix EveView Answer on Stackoverflow