Bug Magnet
Bug Magnet

Reputation: 2668

Jquery next() does not get next element

I have the following code:

<h1><a href="#" class="link">Click here</a></h1>
<div class="acitem"></div>
<div class="acitem2"></div>

<script>
    $(document).ready(function() {
        $('a.link').click(function() {
            var element = $(this).next();

            alert(element.attr('class'));
        });

    });
</script>

When I have the 'click here' link wrapped inside an H1 tag, the alert call returns 'undefined', but if I remove the H1 tag from the link, then the alert call correctly returns 'acitem'. With the H1 tags in place, I have also tried:

$(this).nextUntil('.acitem')

But this still returns 'undefined'.

I am a bit confused as to how the next() function works in JQuery. Anyone know why the next function works correctly only if I remove the H1 tags from the link? Is there something I am doing wrong?

Thanks!

Upvotes: 3

Views: 5298

Answers (2)

Andreas Wong
Andreas Wong

Reputation: 60506

next() works for siblings, in your structure, <a> is the only child <h1> has, so calling next() would technically returns nothing as <a> is the only son of <h1>. Hence why it works if you remove <h1>

Quoting the docs: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

http://api.jquery.com/next/

nextUntil() gets a set of elements starting from the selector up to but excluding the selector given as argument, quoting the docs: Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.

http://api.jquery.com/nextUntil/

About your query, you can call .parent() prior to calling next() to make sure you are getting the sibling of its parent (i.e. his uncle)

<script>
    $(document).ready(function() {
        $('a.link').click(function() {
            var element = $(this).parent().next();

            alert(element.attr('class'));
        });

    });
</script>

Upvotes: 11

Jason Gennaro
Jason Gennaro

Reputation: 34855

@andreas is right about .next and .nextUntil. His solution with .parent is good too.

Another thing you can do is use the Next Adjacent selector ( http://api.jquery.com/next-adjacent-Selector/ )

var element = $('h1 + div');

http://jsfiddle.net/jasongennaro/LMr5E/

Upvotes: 2

Related Questions