Sometimes, we want to get only first class of an HTML element with JavaScript.
In this article, we’ll look at how to get only first class of an HTML element with JavaScript.
How to get only first class of an HTML element with JavaScript?
To get only first class of an HTML element with JavaScript, we can use the classList
property.
For instance, we write:
<div class='foo bar baz'>
</div>
to add a div with multiple classes.
Then we write:
const div = document.querySelector('div')
const [firstClass] = div.classList
console.log(firstClass)
to select the div with querySelector
.
And then we get the first class from div.classList
with destructuring.
Therefore firstClass
is 'foo'
.
Conclusion
To get only first class of an HTML element with JavaScript, we can use the classList
property.