Categories
JavaScript Answers

How to getElementByClass instead of GetElementById with JavaScript?

Spread the love

Sometimes, we want to getElementByClass instead of GetElementById with JavaScript.

In this article, we’ll look at how to getElementByClass instead of GetElementById with JavaScript.

How to getElementByClass instead of GetElementById with JavaScript?

To getElementByClass instead of GetElementById with JavaScript, we use the getElementsByClassName method.

For instance, we write

document.getElementsByClassName("classname")[0].style.display = "none";

to get the first element with class classname with

document.getElementsByClassName("classname")[0]

Then we set the style.display property of it to 'none' to set its display CSS style to none.

Conclusion

To getElementByClass instead of GetElementById with JavaScript, we use the getElementsByClassName method.

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 *