Reputation: 129
So, in dom like this
<div>
<button>Click me</button>
<img src=#>
</div>
<div>
<button>Click me</button>
<img src=#>
</div>
<div>
<button>Click me</button>
<img src=#>
</div>
And script
$("button").click(function() {img.hide() });
How to make js to be executed only in div which contains clicked button? dom is generated, so we cant use specific classes or id's
Upvotes: 3
Views: 333
Reputation: 20740
You can use parent()
and find()
methods.
$("button").click(function () {
$(this).parent().find('img').hide()
});
Or next()
method like following.
$("button").click(function () {
$(this).next('img').hide()
});
Upvotes: 4
Reputation: 9449
I think this is what you want, see fiddle: https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/26/
HTML
<div>
<button>Click me</button>
<img src=#>
</div>
<div>
<button>Click me</button>
<img src=#>
</div>
<div>
<button>Click me</button>
<img src=#>
</div>
JQuery
$("button").click(function() {
$(this).siblings('img').hide();
});
Upvotes: 1
Reputation: 2234
I think you are looking for this..
$("button").click(function() {
$(this).next('img').hide();
});
Upvotes: 1
Reputation: 3435
$("button").click(function() {
$(this).siblings('img').hide();
});
This is only dependent on the current node's structure, and it doesn't matter if the image is before or after the button. You can read more about siblings()
here, and a live code example here
Upvotes: 1
Reputation: 67207
Try to use .next()
at this context,
$("button").click(function () {
$(this).next('img').hide()
});
Since the image that we need to target is the next immediate sibling of the clicked button.
Upvotes: 1