Reputation: 579
I want to select a div using its class, but there are other divs with the same class and with the same buttons that trigger my function, so I only want to select the class where $(this) is in.
I tried .parent, .child, .contains, .find but I didn't figure it out...
$(".btt_class").click(function() {
// I know this is wrong, but to give an idea of what I need
$(".div_class").has(this).append("You cliked here");
});
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
Upvotes: 0
Views: 88
Reputation: 7049
To capture the element of the button being clicked you can do this:
$(".btt_class").click(function() {
$this = $(this); // captures the input element
$div_class_elem = $this.parent(); // goes up one level/element to capture the div element
$div_class_elem.append("You clicked here"); // append this text to the end of the div element
});
Upvotes: 1
Reputation: 1524
this should do the trick: (OOPS, edited to include finding the closest one.)
$(".btt_class").on("click",function(){
myDiv = $(this).parent().closest('div.div_class');
myDiv.append("You clicked here");
});
Upvotes: 1
Reputation: 1454
If I understand your request correctly, your snippet does just what you described: selecting the div, the currently clicked button is in and appending some text to it:
Pleas check out https://jsfiddle.net/4qwy605p/
$(".btt_class").click(function() {
$(".div_class").has(this).append("You cliked here");
});
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
<div class="div_class">
<input class="btt_class" type="button" value="Click me" />
</div>
It works as requested in the fiddle.
Is it possible you just forgot to load jQuery in your snippet?
Upvotes: 1
Reputation: 177
Use .closest() to traverse up the DOM tree up to the specified selector. This should do the trick:
$(this).parent().closest('div').append("You clicked here!")
Upvotes: 0