Reputation: 8582
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
Upvotes: 1
Views: 280
Reputation: 8029
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/
Upvotes: 0
Reputation: 168655
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.
Upvotes: 1
Reputation: 75307
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/
Upvotes: 4