I am trying to select all following elements of an element I choose. They don't necessarily have to be direct siblings of my chosen Element, so .nextAll()
won't work.
Here's an example:
<div class="scope">
<div> <a href="1">1</a> </div>
<div> <a href="2">2</a> </div>
<div> <a href="3">3</a> </div>
<div> <a href="4">4</a> </div>
</div>
<a href="x">NOT THIS</a>
My element is a[href="2"]
, so I want to select a[href="3"]
and a[href="4"]
, but not a[href="x"]
because it's not in my scope.
I found this, but it only fetches one follower, but I need all of them.
I just wrote this, which works great, but it seems odd to me and I am sure that there have to be better solutions than this one:
var $two = $('a[href="2"]');
var selection = [];
var comes_after_2 = false;
$two.closest('.scope').find('a').each(function(){
console.log(this, $two.get(0));
if(comes_after_2){
selection.push(this);
}
if(this == $two.get(0)){
comes_after_2 = true;
}
});
$(selection).css('background', 'red');
Here is a Fiddle to test it: http://jsfiddle.net/mnff40fy/1/
Please feel free to modify it, if there's a better solution. Thank you!