Sunday, April 3, 2011

How to get the other image using jQuery

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?
From stackoverflow
    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).

    thenduks : This is less than ideal.
    Shog9 : Yeah. But, he's only dealing with 5 elements; ideal doesn't buy you much. I liked your answer though.
  • 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).

    Shog9 : ++I like this one.
  • You can get the other in both cases with:

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

    or just:

    $("div.stuff img").remove(this);
    
    thenduks : 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.
    cletus : Er, hate to break it to you but it's ALL DOM manipulation.
  • 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.

  • Take a look at the jQuery eq selector.

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

0 comments:

Post a Comment