Skip to content Skip to sidebar Skip to footer

Reduce Array Of Dom Elements To The Ones With The Deepest Level In Javascript

Let's assume i have HTML markup like this:

Solution 1:

Try using .filter and use .children().length to filter out. See below,

var deepestElements = jQuery('div,p').filter(function () {  
                         return ($(this).children().length == 0);
                       });

Solution 2:

Well yes as SKS suggested use this

jQuery('div,p').filter(function(){
    if($(this).children('div, p').length==0) 
        returntrue;
    })

here the only change is that in children I only look for div and p child nodes... and skip others like span in this case...

Hope this solves your issue...

UPDATE

as you are expecting hope this helps

var types_to_check = 'div,p';
jQuery(types_to_check).filter(function(){
    if($(this).children(types_to_check).length==0) 
        returntrue;
    })

wouldnt this work?

Solution 3:

I found a working solution (JQuery distinct descendants (filter out all parents in result set)).

Code credits to cfedermann:

jQuery.fn.distinctDescendants = function() {
    var nodes = [];
    var parents = [];

    // First, copy over all matched elements to nodes.jQuery(this).each(function(index, Element) {
        nodes.push(Element);
    });

    // Then, for each of these nodes, check if it is parent to some element.for (var i=0; i<nodes.length; i++) {
        var node_to_check = nodes[i];
        jQuery(this).each(function(index, Element) {

            // Skip self comparisons.if (Element == node_to_check) {
                return;
            }

            // Use .tagName to allow .find() to work properly.if((jQuery(node_to_check).find(Element.tagName).length > 0)) {
                if (parents.indexOf(node_to_check) < 0) {
                    parents.push(node_to_check);
                }
            }
        });
    }

    // Finally, construct the result.var result = [];
    for (var i=0; i<nodes.length; i++) {
        var node_to_check = nodes[i];
        if (parents.indexOf(node_to_check) < 0) {
            result.push(node_to_check);
        }
    }

    return result;
};

Post a Comment for "Reduce Array Of Dom Elements To The Ones With The Deepest Level In Javascript"