2

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?

Ari
  • 4,643
  • 5
  • 36
  • 52

2 Answers2

4

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Not sure why it is not working in my case using map and event handler. but working well in js fiddle http://jsfiddle.net/32g5uhrm/1/ – Ari Apr 30 '15 at 22:13
0

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

Ari
  • 4,643
  • 5
  • 36
  • 52