Categories
JavaScript Answers

How to get only first class of an HTML element with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *