1

I have the following html syntax

<ul>
<li class="heading">link</li>
<li>link</li>
<li>link</li>
<li>link</li>
<li>link</li>
<li class="heading">link</li> 
<li>link</li>
<li>link</li>
<li>link</li>
<li class="heading">link</li>
</ul>

I want to select the first .heading element that comes after a normal li element that i click.I tried using the .closest() function but i didn't manage to get it right.With jQuery

asked Oct 24, 2011 at 9:05
1
  • 1
    that was not correct, 'first .heading element that comes after a normal li element that i click.' Commented Oct 24, 2011 at 9:11

3 Answers 3

4

Inside the click handler do:

$(this).nextAll('.heading:first');

nextAll() retrieves all the siblings after the current element that match the selector, so use use the :first selector to only target the first.

nextAll should not be confused with next, which only considers the next element (and will only return it if it matches the given selector).

closest did not work as it examines only the ancestors of the current element, where-as we want to retrieve the siblings.

You can see a JS Fiddle of this working here; http://jsfiddle.net/kuroir/5e3gz/1/

answered Oct 24, 2011 at 9:08
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I was doing the example while you did the answer: jsfiddle.net/kuroir/5e3gz/1
1

Use the "adjacent sibling" selector, which is the plus sign:

$('.heading+li')

This picks allli elements that are immediately after an element with class='heading'.

Note, this is standard CSS, so the above selector will also work in your stylesheets (supported in all browsers except IE6), like so:

.heading+li { .... }

See also http://quirksmode.org/css/selector_adjacent.html for a description of how this selector works.

answered Oct 24, 2011 at 9:11

1 Comment

Thanks for teaching me something new. I saw this in some css styling and wondered what this was for. Now i know!
0

you can do this:

$('li').click(function(){
 $(this).nextAll('li.heading:first'); //This selects the one you want
});

Check this for more help: http://api.jquery.com/next/

answered Oct 24, 2011 at 9:10

1 Comment

next only considers the very next element, unlike nextAll which considers all of them.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.