简体   繁体   中英

How to get all parents of <li> tag onclick of it?

I am designing dynatree so nodes are place in ul and li tags. the problem I am getting is I am not getting parents of clicked li element.

Here is my html code,

<ul class="bulk">

 <li>gp1
   <ul>
    <li>gp2
    <ul>
        <li>gp3
            <ul>
                <li>c1
                <li>c2
                <li>c3
            </ul>
        <li>gp4
    </ul>
  </ul>
 <li>gp5
   <ul>
    <li>gp6
    <ul>
        <li>gp7
            <ul>
                <li>c4
                <ul>
                <li>c5
                <li>c6
                </ul>

            </ul>
        <li>gp8
        <li>gp9
    </ul>
    <li>gp10
</ul>
</ul>

Here is my jquery method

   $('ul.bulk li').click(function(e) 
                { 
                 //alert($(this).find("span.t").text());
                 alert(e.html());
                });

Here is my fiddel http://jsfiddle.net/raghavendram040/ojnLrcjz/

The problem I am getting is if click on gp3 it alerts me 3 times, but I want if I click on gp3 it should alert its parents(gp1 and gp2). Here I place all li and ul dynamically except tag. How to achive this please help me in this

You can do something like

$(function () {
    $('ul.bulk li').click(function (e) {
        if($(e.target).is(this)){
            $(this).parentsUntil('.bulk', 'li').each(function(){
                alert(this.firstChild.nodeValue)
            })
        }
    });
});

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM