tags:

views:

178

answers:

5

Hi,

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?
+1  A: 
  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).

Shog9
This is less than ideal.
thenduks
Yeah. But, he's only dealing with 5 elements; ideal doesn't buy you much. I liked your answer though.
Shog9
+2  A: 

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).

Ben Alpert
++I like this one.
Shog9
+2  A: 

You can get the other in both cases with:

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

or just:

$("div.stuff img").remove(this);
cletus
I removed my answer because this is the same thing and I misread the example as being with an id :)... Personally I prefer .not(selector_or_element) to .remove because remove feels like it's a DOM manipulator.
thenduks
Er, hate to break it to you but it's ALL DOM manipulation.
cletus
A: 

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.

Steven Surowiec
+1  A: 

Take a look at the jQuery eq selector.

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