Reputation: 9828
I wish to know an elegant solution for clicking on a certain class within a certain div
$( ".clickdiv" ).on( "click", function () { //do stuff }
This works for any class of clickdiv
. However, I want it only to work if the clickdiv
is nested with certain div
<div class="certaindiv">
...bunch of divs
<div class="clickdiv">
...bunch of close divs
<div>
Upvotes: 0
Views: 29
Reputation: 115212
Update your selector as .certaindiv .clickdiv
that it will only select .clickdiv
inside .certaindiv
$(".certaindiv .clickdiv").on("click", function() {
alert('clicked');
//do stuff
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="certaindiv">
...bunch of divs
<div class="clickdiv">
shdhsghdh
</div>
...bunch of close divs
</div>
<div class="clickdiv">
shdhsghdh
</div>
Upvotes: 1
Reputation: 7318
If the elements are on the page when it loads and never change, you can simply modify your selector:
$( ".certaindiv .clickdiv" ).on( "click", function () { /*do stuff*/ }
If the elements are dynamically created, you can use event delegation:
$( ".certaindiv" ).on( "click", ".clickdiv", function () { /*do stuff*/ }
Upvotes: 1