Reputation: 7388
Here is a part of my html. (it is written using ejs)
<div class="objAddDiv">
<tr><td><button class="addObj">Do this action</button></td></tr>
<table><div class="objects"></div></table>
</div>
I have several objAddDiv divs on this page. Each has the same structure inside of it. I use .append()
to add more ejs to .objects
. I am having a hard time adding to only the .objects
div that is inside of the same div as the button. I tried doing the following
".addObj click": function(el, element){
$(".addObj").closest(".objAddDiv").find(".objects").append(//my ejs utility here)
}
The problem is that $(".addObj").closest(".objAddDiv")
returns all .objAddDiv
on the page. I have looked at the jquery documentation for .closest
and it says closest should only return one element. Is there a better way to do this? What am I doing wrong. (these are not my real class names btw)
Upvotes: 0
Views: 169
Reputation: 7388
Here is the answer that I figured out (for anyone who comes next) I needed to use the element I passed into the function:
el.closest(".objAddDiv").find(".objects").append(//ejs append stuff)
Upvotes: -1
Reputation: 35793
It's because you are calling that method on every element with a class of 'addObj':
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
So you get the closest objAddDiv
to each addObj
element.
Assuming you are doing this inside the click event of the button use this to get the correct element:
$(this).closest(".objAddDiv").find(".objects").append(//my ejs utility here)
Upvotes: 3