jQuery获得最深层的内在元素

时间:2015-10-27 12:36:20

标签: jquery html

找到大多数内部ul以插入更多li个。我不确定ul的深度。

是否有任何jQuery API可以找到div的大多数inner元素。

<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>

1 个答案:

答案 0 :(得分:1)

此函数在ul中查找叶context元素,并为它们执行某些操作:

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
        }
    });
}

如果您想通过深度编号执行此操作,请按以下方式执行此操作:

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
    });
}