Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Select element 2 positions further - another way to .next().next()

I am searching for a way how I could select a div element which is not the direct next one to the one which is "selected" by a click function.

<div id="click">(siblings)</div><div>text</div><div id="get this one"></div>

Now I would like to select the one with the id "get this one" - in my code this id is not available. All the divs have the same class and do have siblings.
I could select the third one by $(this).next().next() but I think it's not the best way to do it.
Also there can be divs before the one which is clicked - so it's not necessarily the first one.

I tried the :nth-child selector but didn't find a solution.
Later I also may want to select the 13th one after the click one (or the 23th, 65th and so on). This means I would like to have a rather dynamic solution to this problem.

Thanks for your help,
Phil

like image 541
Phil Avatar asked Sep 09 '10 12:09

Phil


People also ask

How do I set relative position in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

What is .next in jQuery?

The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

How do you select an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.


1 Answers

You can use .nextAll() with .eq() for your dynamic approach, like this:

$(this).nextAll().eq(1) //0 based index, this would be .next().next()

This would allow you to get n siblings forward, which seems to be what you're after.

like image 145
Nick Craver Avatar answered Oct 06 '22 23:10

Nick Craver