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

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


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');

Tags:

Javascript