bonaca bonaca - 4 months ago 14
jQuery Question

cannot select children elements of a specific class

Why this doesn't work

<div class='folder lev1'>323</div>
<div class='folder lev2'>525</div>
<div class='file lev3'>727</div>
<div class='file lev3'>929</div>
<div class='folder lev1'>end</div>


js

$(".lev1").click(function(){
if ($(this).next().is(":visible")) {
$(this).nextUntil(".lev1").hide(); // works
}
else {
$(this).children(".lev2").show(); // doesn't work
$(this).find(".lev2").show(); // also tried - doesn't work
console.log("323"); // works
}
});


Console is without errors.

Answer

In your example, .lev1 doesn't have any chlidren. has siblings.

$(".lev1").click(function(){
    if ($(this).next().is(":visible")) {
        $(this).nextUntil(".lev1").hide(); // works
    }
    else {
        $(this).siblings(".lev2").show();  // works
    }
});

Or, if you want the next .lev2 be shown:

$(".lev1").click(function(){
    if ($(this).next().is(":visible")) {
        $(this).nextUntil(".lev1").hide(); // works
    }
    else {
        $(this).nextAll(".lev2").show();  // works
    }
});