views:

45

answers:

2

Hey,

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 did'nt find a solution. Later I also may want to select the 13th one after the clicke 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

A: 

It seems that $(this).parent().find('div').eq(2).attr('id') should work.

UPDATE( Added find('div') )

d2burke
This would always result in an empty element set, `.parent()` selects a single element, not siblings :)
Nick Craver
Before, your answer had nextAll('eq:2'). Would this work the same way as what you have for your answer now? What's the difference?
d2burke
@d2burke - You're getting the 3rd element in the parent no matter what...this isn't relative to the *current* element, it just gets the 3rd one, no matter which you clicked. Also my answer used `:eq(1)` for the 2nd, it's a 0-based index :)
Nick Craver
@Nick - Ah, yes. I see (regarding the relative selection). I understand the index being based on 0, but I was more referring to the fact that you had the "eq:1" in quotes before...and I wondered if that were just another way to write it. Thanks for pointing out the difference between your answer and mine. Yours it more flexible for sure.
d2burke
@d2burke - You can use [`:eq(2)`](http://api.jquery.com/eq-selector/) as a selector as well, rather than a function call, but when I re-read the question and saw he wanted it dynamic..it's much easier to use `.eq(variable)` rather than `".eq(" + variable + ")"`, and it's faster to boot.
Nick Craver
Nice, that makes sense. thanks Nick
d2burke
+4  A: 

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.

Nick Craver
Ok, now i feel like an ideot. It's so easy - and it works, of course. It makes so much sense that i hate me for not getting it working by myself. But thank you very much :)
Phil