jQuery Tip: The .next() Selector
18/07/09 :: Posted by RobI just thought I would take a quick moment to explain the awesome next() feature of jQuery.
I recently used it for a site I was coding for the wonderful @divinefusion, I will link when its live.
Let’s make some example code.
<div id="parent">
<h3 class="box">box</h3>
<p>Some Text</p>
<h3 class="box">box</h3>
<p>Some Text</p>
<h3 class="box">box</h3>
<p>Some Text</p>
</div> |
Say we wanted to slide up the paragraph when the h3 with the Class of “box” is clicked, but we wont want ALL the paragraphs to slide up. Have a look at the next bit of code:
$(function) { $(".box").click(function () { $(this).next().slideUp("fast"); }); }); |
What happens here is we select the h3 and listen for it to be clicked. When it is clicked we target the next element. We do this by using “this” which means the item that was just clicked, (in this case the h3 with the Class of box) and then we add “next” which hops the selection to the next item, which in this case is the paragraph tag. We then tell the paragraph to slide up quickly.
Now you can see how this will only work for the P directly next in the document to the clicked element. Very handy. This will only work where the elements are siblings, this means they are next to each other, the same children of the parent element, as the example shows. Both the box and the paragraph are children of the wrap div. This makes them siblings.
Hopefully we can expand on this to show some more examples, but give it a go!
This entry was posted on Saturday, July 18th, 2009 at 11:45 pm and is filed under Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



