Laxmikant
Laxmikant

Reputation: 2216

jQuery get deepest inner element

Find most inner ul to insert some more lis. I'm not sure about the depth of th ul.

Is there any jQuery API to find most inner element of the divs.

<ul class="optiongroup" "label"="Solutions">
   <li><label>Solutions</label></li>
   <ul class="optiongroup" "label"="Other Solutions">
   <li><label>Other Solutions</label></li>
      <ul class="optiongroup" "label"="Publishing">       <li><label>Publishing</label></li>
  // Append some <li>'s here 
      </ul>
   </ul>
</ul>

Upvotes: 0

Views: 178

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76601

This function finds the leaf ul elements in a context and does something for them:

function handleInnerUL(context) {
    //finds all inner ul elements
    var innerContext = context.find("ul");
    //processes inner ul elements
    innerContext.each(function() {
        //if ul does not have inner ul, then do something
        if (innerContext.find("ul").length === 0) {
            //Do something
        }
    });
}

If you want to do this by depth number, then do it this way:

handleInnerUL(context) {
    //initialize helpers
    var innerSelector = "ul";
    var innerContext = context.find(innerSelector);
    var depthmostContext = null;
    //while inner level exists, process into it
    while (innerContext.length > 0) {
        //store the innermost depth ul found
        depthmostContext = innerContext;
        innerSelector += " ul";
        innerContext = context.find(innerSelector);
    }
    //do something for them
    depthmostContext.each(function() {
        //do something
    });
}

Upvotes: 1

Related Questions