Multiple selector of elements selected via tree traversal

$('.myclass').parent().prev().prev();
$('.myclass').parent().prev();
$('.myclass');
$('.myclass').parent().next();
$('.myclass').parent().next().next();

How to select all this elements in only one line via jQuery ?

I thought of this solution, but hope that there is something better :

$('.myclass').parent().prev().prev().addClass('select_me');
$('.myclass').parent().prev().addClass('select_me');
$('.myclass').addClass('select_me');
$('.myclass').parent().next().addClass('select_me');
$('.myclass').parent().next().next().addClass('select_me');

$('.select_me').fadeOut(); // I select all the previous elements in only 1 line.

Answers


You can do it using filter() and index()

Live Demo

idx = $('.myclass').parent().index();
$('.myclass').parent().siblings().addBack().filter(function(){    
    return  $(this).index() > idx -3 && $(this).index() < idx + 3;
}).addClass('select_me');

Live Demo

$('.myclass').each(function(){    
    currentObject = $(this);
    parent = $(this).parent();
    $(this).parent().siblings().filter(function(){
      return  $(this).index() > parent.index() -3 && $(this).index() < parent.index() + 3;
    }).add(currentObject).addClass('select_me');
});

Like this?

$.merge($('.myclass'), $('.myclass').parent().siblings()).fadeOut();

Need Your Help

NSMutableArray sortedArrayUsingDescriptors: requires intermediate results array

ios objective-c nsmutablearray nsarray

sortedarrayusingdescriptors doesn't appear to do an in-place sort as I'd hoped.

Confusing error from | xargs sed

git bash replace sed xargs

I have a little find-replace utility around git. Let's ignore suggestions for a different approach ATM. I'm really trying to understand this error from sed. Take a look at the command