payal arora payal arora - 1 year ago 74
Javascript Question

How to find next similar sibling moving down in the dom tree

What I need over here is while positioned on one of the

elements I want to jump to the next
element. How can I achieve this?

<dl class="accordion">
<dt>Select Category</dt>

<dt>select product</dt>

(function($) {
var allPanels = $('.accordion > dd').hide();
$('.accordion > dd:first-of-type').show();
$('.accordion > dt:first-of-type').addClass('accordion-active');

jQuery('.accordion > dt').on('click', function() {
$this = $(this);
$target = $;
if (!$this.hasClass('accordion-active')) {
jQuery('.accordion > dt').removeClass('accordion-active');
return false;

Answer Source

What appears to be the obvious option in jquery: .next("dt") is not, because .next() always only returns the very next sibling, applying a filter .next(filter) still only returns the very next sibling, but only if it matches the filter

jQuery provides two alternatives: .nextUntil() and .nextAll()

These can be used as:

nextdt = thisdt.nextUntil("dt").next();
nextdt = thisdt.nextAll("dt").first();

where nextUntil gets the next siblings until the match (so you then need another next()) and nextAll gets all the matching (so you then need first()).

In the question's code, this gives the following update:

jQuery('.accordion > dt').on('click', function() {
    $this = $(this);
    $target = $this.nextAll("dt").first(); 

Example fiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download