Take the 2-minute tour ×

I have this structure:

    <a> link .. </a>
    <span> text </span>

I'm adding a click event on both the <span> and <a> elements and I'm trying to select the nested <ul> using $(this).next("ul");

It works for the span, but not for the link. What am I doing wrong here?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

A click handler on the anchor will not see the UL if you're using next to grab it, since next will only select the very next sibling. You can try:





share|improve this answer
nextAll() works for me, thank you. But it's weird that next() is accepting arguments, if it returns the very next element anyway. –  Alex Nov 13 '10 at 3:11
@Alex - the argument it accepts means 'return the very next element only if it matches the passed selector. It is extremely unintuitive, and this question has popped up hundreds of times in various incarnations for the very same reason. –  karim79 Nov 13 '10 at 3:13
ah I see now. thanks :) –  Alex Nov 13 '10 at 3:16
That explains why my code didn't work the other day :-P. One question thou, the nextAll returns several elements, right (all the next ones that are a match, right)? Will then nextAll('ul:first') return the element you're searching for? –  Alxandr Nov 13 '10 at 3:16
@Alexandr - Yes. I did, however, assume that there was just one UL on the same level (based on the markup in the question) so I omitted the :first pseudo-selector. (I did think about including it though :) –  karim79 Nov 13 '10 at 3:18
add comment

Your Answer


