Skip to content Skip to sidebar Skip to footer

Select A Child Of A Child

Why can't I select a child of a child in jQuery? I want to add a class to a child of a child using .children() method and the > selector. See code below: $(function(){ /

Solution 1:

From the JQuery documentation on .children():

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

You really don't even need to be using .children() for this at all. The much simpler solution is to just provide context for your queries by passing a second argument to JQuery after the selector.

$(function(){
        // main expansion element
        $(".expander").click(function() {
        
           // Just for demonstration: *************************************************// 2 because of <span> and <ul>console.log($(this).children().length);          
           
           // 0 because anything beyond children isn't returned in the first placeconsole.log($(this).children("ul > li").length); 
           // *************************************************************************//  By passing "this" as the second argument to JQuery, after the selector,//  it sets the context for the search to only "this", so the entire DOM//  is not searched, just the object that "this" is bound to.var subShown = $("ul > li", this).hasClass("show");
            if (!subShown) {
                $(".indented", this).slideDown('100').addClass("show");
                $(".caret", this).addClass("reversedCaret");
            } else {
                $(".indented", this).slideUp('100').removeClass("show");
                $(".caret", this).removeClass("reversedCaret");
            }
        });
    });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="expander"><spanclass="caret downCaret right visibleCaret">+</span><ul><liclass="category">Item 1<ahref="http://www.google.com"></a></li><liclass="indented"><ahref="http://www.google.com">Item 2</a></li><liclass="indented"><ahref="http://www.google.com">Item 3</a></li></ul></div>

Solution 2:

you can use .find('>ul>li'), example:

var expander = $(".expander")

expander.on('click', function(){
  var li = expender.find('>ul>li')
  li.hasClass("show")
})

Solution 3:

If you still want to approach it as you are (and not as the given answer does, which is better by the way), then change this

$(this).children("ul > li")

to this:

$(this).children('ul').children()

Selecting children of ul that is.

Solution 4:

.querySelector

document.querySelector("section > div").classList.add("my-gray");
.my-gray{
  background: gray;
}
<section>
Foo
<div>
Bar
</div></section>

Post a Comment for "Select A Child Of A Child"