Max Malberg
Max Malberg

Reputation: 197

jQuery: nextAll independent of parents

I'm building a small lightbox-plugin (just for fun) and if the user presses a key, it should open (simulate click) the next link having the same "rel"-attribute.

 .nextAll('.box[rel="'+boxed+'"]').eq(0).click();

The code above works for the following example:

<a href="/1.jpg" class="box" rel="box-abc123">One</a>
<a href="/2.jpg" class="box" rel="box-abc123">Two</a>
<a href="/3.jpg" class="box" rel="box-abc123">Three</a>

But if the images are in different parent-elements, like…

<header><a href="/1.jpg" class="box" rel="box-abc123">One</a></header>
<section><a href="/2.jpg" class="box" rel="box-abc123">Two</a></section>
<footer><a href="/3.jpg" class="box" rel="box-abc123">Three</a></footer>

…it doesn't work. Of course I could use parent() to jump, but I want to build it completely independent of parent-elements (as there aren't some always). Is there a way to find the next element independent of any parent-elements? Does anybody know how to solve this? Thank you!

Upvotes: 1

Views: 551

Answers (2)

YogeshWaran
YogeshWaran

Reputation: 2281

if you don't want to use parent element the use slice to get next all elements

$('a.box[rel="'+boxed+'"]').slice($('a.box[rel="'+boxed+'"]').index(this))

working fiddle: http://jsfiddle.net/aaWHt/2/

Upvotes: 1

billyonecan
billyonecan

Reputation: 20260

I had a similar problem to this - basically trying to get the next element in a set regardless of where they appear in the dom tree. The best solution was to loop over these elements initially, and give them an id, which could then be used to select the next element.

$boxSelector = $('.box[rel="box-abc123"]');

$boxSelector.each(function(i, v) {
  $(this).prop('id', 'box-' + ++i);
});

You can then get the id of the next .box by doing something similar to this:

var nextId = '';
var boxLength = $boxSelector.length;

$boxSelector.on('click', function() {
  var thisIndex = parseInt(this.id.replace(/[^\d]+/, ''));
  nextId = (thisIndex == boxLength) ? 1 : thisIndex+1;
});

You can then select the next element using:

$('#box-' + nextId);

I understand that this doesn't directly answer your question, but you should be able to apply the same principles to achieve the desired result.

Upvotes: 0

Related Questions