How to get only one element by class name with JavaScript?
javascript
Solution
`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');
Problem
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.