user1502434 user1502434 - 18 days ago 6
Javascript Question

jquery if statement to check if element is within a specific parent div

I have alot of elements with class of .button all over my layout. Upon a click of the element with class of button, I need to check first that the element is within the parent div of either box1 or box2.

A short example would be... if the clicked button is within the box1 div && (another condition) then do something. Would it be best to use the combination of .closet and .length to check if the button is within a certain div?

<div id="box1">
<div id="column1">
<div class="round_button"></div>
<div style="background: #000">
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
</div>
</div>
<div>

<div id="box2">
<div id="column2">
<div class="round_button"></div>
<div style="background: #000">
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
<div class="button"></div>
</div>
</div>
<div>

Answer

In addition to the answer above, if there are a number of buttons, and instead of binding an event separately to each, you just want to attach once, based upon its ancestor, you can do something like this:

$(".button").click(function() {
  if ($(this).is("#box1 *")) {}
});