How to get only one element by class name with 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-like HTMLCollection 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');

Leave a Comment