How to Show/Hide Element by Class using JavaScript

The display property is used to control the visibility of HTML elements with CSS. Sometimes we may require to change the visibility of elements dynamically in JavaScript. The element ID or class can be used to select and Show/Hide DIV using JavaScript.

In this code snippet, we will show you how to hide or show element by class with JavaScript. Use the Document:getElementsByClassName() method to show and hide element by class name using JavaScript.

HTML DIV Element:

<div class="my-div">
    ...
</div>

Show Element by Class in JavaScript:

document.getElementsByClassName('my-div')[0].style.display = 'block';

Hide Element by Class in JavaScript:

document.getElementsByClassName('my-div')[0].style.display = 'none';

Leave a reply

keyboard_double_arrow_up