Jon
Jon

Reputation: 6541

Is this how I should use the .next( [selector] ) in jQuery?

Using jQuery, I have selected an <a> inside a div and want to use $(this) to select the next div (I guess this makes it an uncle?).

I want to use the same class name for all my content so I want to use only relative to $(this).

Here's an example of the behavior I am after:

<div><a>click</a></div>
<div> SELECT THIS DIV after click a </div>  (real code below)

I have been playing around and it works fine if I don't close the div around the <a>. .next('div") finds the div after the </a>, but I need to close the div of the <a>. (So I guess this makes the <a> a child of the div I am in.)

So I need to access the uncle div of the one I'm in? How would I do that -

Here's what I have been playing with so far:

js:

 $(document).ready(function() {
  $('.demo > .row').hide();  
  $('.demo > .box > a').click(function() {
    $(this).next().slideToggle('fast')
    .siblings('div:visible').slideUp('fast');
  });
});

html:

<div class="demo">
    <div class="box"><a>Title 1</a></div>
    <div class="row">
        <ul >
            <li> <a >  <img >  </a></li>
        </ul>
    </div>
</div>

Upvotes: 3

Views: 156

Answers (4)

gen_Eric
gen_Eric

Reputation: 227200

To get the 'uncle', you need to first get the parent, then the sibling.

$(this).parent('div').next('div')

Or, if the a is nested in other elements, you can use closest to get the parent div.

$(this).closest('div').next('div')

Upvotes: 0

Py.
Py.

Reputation: 3599

Have you tried using parent?

Something like $(this).parent().next();

Upvotes: 0

Jon
Jon

Reputation: 437336

You need to traverse the document tree upwards from the "current" <a> to its parent <div>, and then sideways to find the next <div>:

$(this).closest("div").next().slideToggle('fast')
       .siblings('div:visible').slideUp('fast');

Traversing upwards can be done with a number of functions; I prefer closest because it's less susceptive to breaking if your markup changes.

Also, note that if you click on an anchor child of the last sibling <div>, the next() call will not produce any element.

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 237837

Have a look at the traversal functions provided by jQuery. In this case, you need parent followed by next:

$(this).parent().next().slideToggle...

Upvotes: 3

Related Questions