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!
next()works for siblings, in your structure,<a>is the only child<h1>has, so callingnext()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 callingnext()to make sure you are getting the sibling of its parent (i.e. his uncle)