Skip to content Skip to sidebar Skip to footer

Detect If The Element Im Currently In Is The Youngest Son/grandson/grandgrand Son Of An Element

I am looping around span elements which belongs to frag class. I wanted to detect if the frag element im currently in is the youngest son/grandson/grandgrand son(from left to right

Solution 1:

Try changing validAncest with:

var validAncest = $elem.parents('.cond').filter(function(i){
    return /^\s*(if|else\s+if)/.test($(this).text());
}).filter(function(i){
    var generations = 1,
    $elemCrawl = $('.frag').eq(fragNum).parent();

    while ($elemCrawl[0] && $elemCrawl[0] !== this) {
        if (!$elemCrawl.is(':last-child')) {return false;}
        generations++;
        $elemCrawl = $elemCrawl.parent();
    }

    if ($elemCrawl[0] && generations < 4) {
        return true;
    }
});

This should include:

  1. The parent of $elem provided it starts with 'if'/'else if'
  2. The grandparent provided it starts with 'if'/'else if' AND the parent of $elem is the last child of this grandparent
  3. The great-grandparent provided it starts with 'if'/'else if' AND the parent of $elem is the last child of the intermediate grandparent AND that grandparent is the last child of the great-grandparent

Post a Comment for "Detect If The Element Im Currently In Is The Youngest Son/grandson/grandgrand Son Of An Element"