0

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>

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Ugh friday afternoon strikes again... Thanks
@myol : glad to help ;)
1

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*/ }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.