Hasen
Hasen

Reputation: 12324

Jquery get nearest element below selected and by selector

This seems to have been asked about a billion times but I couldn't find how to specifically do what I want to do, even though it is very simple:

<button></button>
<button></button>
<img />

Basically I want to click either button and have them update the image. With this code:

$(this).next('img').attr("src","newimage.png");

The lower button works but the upper button does not. It seems to logically be selecting the 'next' element, but however illogically not by selector since otherwise the top button would work as it would go on to find the next element that IS an img element.

I tried other stuff like closest() but that doesn't appear to do what it's name suggests it would either.

Upvotes: 0

Views: 59

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337600

The issue is because next() looks for the following sibling only. To fix this you could use nextAll() along with :first to retrieve the img you require:

$('button').click(function() {
  $(this).nextAll('img:first').attr("src", 'https://i.imgur.com/CaTFJ0z.png');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>A</button>
<button>B</button><br />
<img src="https://i.imgur.com/RGv7GmZ.png" />

Upvotes: 2

Related Questions