简体   繁体   中英

Fire onclick event based on class of another div?

I have a javascript button that fires an onclick event but i only want it to do that if another div contains a class called "active".

so I have this structure:

<div id="div1">
<div id="someid1" class="design"></div>
<div id="someid2" class="design"></div>
<div id="someid3" class="design"></div>
<div id="someid4" class="design"></div>
</div>

that based on other page activity any can change to class="active"

<div id="someid2" class="design active">

The button is:

<button type="button" id="button1" onclick="dosomething">Click me</button>

but i only want the dosomething to work if the above any of the divs has the active class, and throw an alert if it does not. I am not terribly good with javascript and could use some help.

Hope this is clear. Thanks.

Assuming dosomething is a function, you could just check for the class inside it

function dosomething() {
    if ( document.querySelector('#parentid .active') ) {
        // do stuff
    }
}

querySelector returns null if not found, which is falsy.

document.querySelector documentation

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