简体   繁体   中英

How to check if the class is added to div element using react or javascript?

I want to close the list menu if a user clicks anywhere outside the list menu. This means that when clicking anywhere on the document except the list, the list menu should be closed.

To do that, I have the method defined like below (react),

handle_click = (event) => {
    if (this.list_menu_ref.current.contains(event.target)) {
        return;
    }
    this.props.on_close(); //this method handles closing the list menu
};

This works fine. now I have an overlay sometimes when this is active and list menu opens and also when a user clicks anywhere on the document, I don't want the list menu to close in that case.

from the domnode we can identify this overlay with the class active is visible like below,

<div id="overlay_root" class="active>
    //some content
</div>

So whenever this active class gets added to the div with id "overlay_root" and a user clicks on the document I don't want the list menu to close.

How can I do it? could someone help me with this?

Thanks

How to check if the class is added to div element using react or javascript?

That's a way to check if element contains a class and remove it

if ( document.getElementById("overlay_root").classList.contains('active') ){
  document.getElementById("overlay_root").classList.remove('active');
}

Let's assume you have two class

active : for showing list

and

de-active : for hiding list

and here is your list

<div id="overlay_root" class="active" onClick = {e => yourMethod(e)}>
    //some content
</div>

and your method is like

   yourMethod = (e)=>{
       this.setState(listMenuToggle : !this.state.listMenuToggle )
    }

here you can see you have a state called listMenuToggle , it may contains true or false . when it's true you will show your list and for false close the list. so your list will be somethings like

<div id="overlay_root" class={this.state.listMenuToggle ? 'active' : 'de-active' } onClick = {e => yourMethod(e)}>
    //some content
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM