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.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s). Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur.
Using JavaScript – querySelector() function The querySelectorAll() method returns all elements within the document having the same class. To get the first element that matches the specified selector, you can use the querySelector() method.
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With