david_o
david_o

Reputation: 45

jQuery Tree Traversing to select next div

Looking for a way to accomplish populating a div with jQuery, traversing.. which I'm no good at.

My code has a series of 6 boxes and then a content box.. another 6 boxes and a content box like so:

<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='content'></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='box'><img src='x' /></div>
<div class='content'></div>

What I am looking for is when somebody clicks on the image - it populates the next .content div only.

Thanks in advance.

=== For Hugo.. The closest I got, which obviously populates all the content boxes is:

$(".box img").click(function(){
                $(this).parent().parent().find(".content").html("X");
            });

Upvotes: 2

Views: 304

Answers (3)

Blazemonger
Blazemonger

Reputation: 92893

$('img').click(function() {
  var $nextdiv = $(this).parent().nextUntil('.content').addBack().last().next();
  // do something with it
});

http://jsfiddle.net/mblase75/gRKfa/

http://api.jquery.com/nextUntil

(.nextAll().first() is rather less complicated, though.)

Upvotes: 0

Ram
Ram

Reputation: 144679

$('.box img').click(function(){
   $(this).parent().nextAll('.content').first().text('...');
})

Upvotes: 3

Jon
Jon

Reputation: 437336

You need to use the appropriate traversal functions for this. The "best" version depends on your markup and the relative stability of its various pieces, but for now let's just work with the HTML you give.

Starting from any <img>, you want to move up to its parent .box and then look for the next .content. Translating to jQuery:

$(this).parent().nextAll(".content").first()

Upvotes: 1

Related Questions