Using jQuery is there a way to find the farthest (deepest, or most nested) child element?

后端 未结 5 756
南笙
南笙 2020-12-11 11:25

If I have a set of elements:

Text 1
5条回答
  •  清歌不尽
    2020-12-11 11:57

    I think this will work for you.

    var deepestLevel = 0;
    var deepestLevelText = "";
    
    function findDeepNested(element, currentLevel) {
        if ((element.children().length == 0) && (deepestLevel < currentLevel)) {
            // No children and current level is deeper than previous most nested level
            deepestLevelText="
  • " + element.text() + "
  • "; } else { // there are children, keep diving element.children().each( function () { findDeepNested($(this), currentLevel + 1); }); } } $(".start").each( function () { deepestLevel = 0; deepestLevelText = ""; findDeepNested($(this), 0); $("#results").append(deepestLevelText); });

    Fiddle

提交回复
热议问题