mrblah
mrblah

Reputation: 103707

How to get the other image using jQuery

My DOM looks like this:

<div class="stuff">
  <a href="#"><img src=""></a> <b>hello</b>
  <a href="#"><img src=""></a>
</div>

Sometimes I have a reference on the first image, and sometimes on the second image.

  1. When I have the first image using $() how do I select the second image?
  2. When I have the second image using $() how to I select the 1st image?

Upvotes: 0

Views: 798

Answers (5)

Shog9
Shog9

Reputation: 159718

  1. .parent().nextAll("a").children("img")
  2. .parent().prevAll("a").children("img")

This is a fairly inelegant way to accomplish it, but it's quite explicit as to what you're looking for - almost like XPath. Once you start dealing with more than two links, you may find a technique such as those described by Ben Alpert or cletus to be more flexible (less dependent on a strict hierarchy).

Upvotes: 1

ceejayoz
ceejayoz

Reputation: 180176

Take a look at the jQuery eq selector.

var first = $('.stuff img:eq(0)');
var second = $('.stuff img:eq(1)');

Upvotes: 2

Steven Surowiec
Steven Surowiec

Reputation: 10220

You should be able to use something along the lines of

$('DIV.stuff:first-child')
$('DIV.stuff:nth-child(3)'

This will return the anchor tags which can be used to access the images. The second is nth-child(3) because nth-child(2) will return the bold tag. The ideal way though would be to apply a class or id to each image or anchor.

Upvotes: -1

cletus
cletus

Reputation: 625467

You can get the other in both cases with:

$(this).parent().siblings().children("img").remove(this);

or just:

$("div.stuff img").remove(this);

Upvotes: 2

Sophie Alpert
Sophie Alpert

Reputation: 143204

Given myImage as a reference to one of the images, $(".stuff img").not(myImage) should give you the other (or others, if you have more than two images).

Upvotes: 2

Related Questions