rob.m rob.m - 12 days ago 7
Javascript Question

.parent().next() not working

If I do:

$("a").on("click", function(e) {
$(this).parent().find("ul").toggleClass("closed opened");
e.preventDefault();
});


It works but it will target all uls of the parent

so I am doing

$("a").on("click", function(e) {
$(this).parent().next("ul").toggleClass("closed opened");
e.preventDefault();
});


But this doesn't work, I get no errors at all.

If I do the following works on JSFiddle using the html used here:

$("a").on("click", function(e) {
$(this).next("ul").toggleClass("closed opened");
e.preventDefault();
});


It doesn't make sense. I need to target the first child of the parent element that I am clicking.

<ul>
<li><a href="">Text</a>
<ul class="closed">
<li><a href="">Two</a>
<ul class="closed">
<li><a href="">Three</a>
<ul class="closed">
<li><a href="">Four</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

.closed {
display: none;
}

.opened {
display: block;
}


JSFiddle with the html used in the example

UPDATE

This is the JSFidle with the real html

Answer

what you are looking for is siblings() instead of next()

$("a").on("click", function(e) {
    $(this).siblings("ul").toggleClass("closed opened");
    e.preventDefault();
});

The reason why next is not working with you is in the way that you tried to use it. you have used parent() first, then asked to get the next() element of type ul, and this doesn't match the way next should work.

cause in your DOM structure, the next element after going up to the parent will be your anchor tag, and next will only match with just the first element in your dom, not with the first element that matches with your selector, and this is the root cause of your mis-usage.

consider the official description of how next with a selector is working:

The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the immediately following sibling matches the selector, it remains in the newly constructed jQuery object; otherwise, it is excluded.