Clicked

Clicked

Clicked

Get All Parents Info Up Until Specified Parent

762 Views Asked by At

I have this html codes example:

<html>
    <body>
        <div>
            <div id="stophere">
               <h4 class="parentclass"> 
                <span class="target">Clicked</span>
               </h4>
            </div>
        </div>
    </body>
</html>

From the html codes example above, I want to get all parents' tag name of class target (when receiving click event) down from div with id stophere.

I tried this code:

$(ev.target).parents()
            .map(function() {
            return this.tagName;
            })
            .get()
            .join( ", " );

But it includes all parents' tag names above stophere. While the result I want is only 1 div and 1 h4.

What is the correct way to get all parents of target down from stophere?

2

There are 2 best solutions below

1
adeneo On BEST ANSWER

You can use the parentsUntil method for that

$(ev.target).parentsUntil($('#stophere').parent())

Note that it's non-inclusive, so we pass the parent of #stophere to include that element as well

FIDDLE

0
Ari On

I don't claim that this is a good solution, but can be used if adeneo's solution is failed in your situation like in my case.

This code is checking whether the traversing limit is containing that limit line itself or not, by using find() method:

    jQuery('html').on("click", function (ev) {
        var elemparentid = jQuery(ev.target).closest("[id]").attr("id");
        var thisparents = jQuery(ev.target).parents()
            .map(function () {
// check if traversing limit is a children of current element or not, by using find() method
            if (jQuery(this).find("#" + elemparentid).length < 1) {
                return this.tagName;
            }
        }).get()
            .join(", ");
        alert(thisparents);
    });

FIDDLE