Assuming I have a JQuery object stored in $e obtained through this selector:
var $e = $("input[type='text'][value='" + v + "']");
v represents the $(this).val() which I obtain inside an .each() iteration but it doesn’t actually matter, it can be any numeric value.
I want to create a JQuery set of elements containing $e, the DOM element which comes after it, and the 6 DOM elements previous to $e.
The function itself works perfectly fine, I’m using this code for each iteration:
var $e = $("input[type='text'][value='" + v + "']");
$e = $e.add($e.next());
for (i=0;i<6;i++)
$e = $e.add($e.prev());
$e.remove();
I guess it’s a little bit hard to explain, so take a look at this JSFiddle.
I’ve wrapped the code above inside an anonymous function bound to the the Remove line 2 button which will pass a fixed v value to my script.
I’m a starter with JQuery and even after taking a good read at JQuery Selectors page I couldn’t find a simpler way to do this. I thought that the .siblings(), or more specifically JQuery(‘prev ~ siblings’) could do it in a simpler way if I could specify the range of the jquery objects array but I couldn’t figure out how.
The HTML is generated through a PHP template which I’d rather avoid editing, so I’ll accept answers which do not include wrapping the given elements inside a container/wrapper.
Is there any simpler way to select the 6 previous elements of a given JQuery selector without wrapping them inside any container or wrapper?
Try using
.prevAlland slice the elements you need. See below,DEMO
Edit: Added
$e.add($e.next())to add next element.