tags:

views:

201

answers:

3

Dear all I am using JQuery I need to extract the List' Id name.

<ul id="nav">
     <li id="outer1m"><a href="#url"><b class="">outer1</b></a></li> 
     <li id="outer2m"><a href="#url"><b class="">outer2</b></a></li> 

     <li id="outer3m"><a href="#url"><b class="">outer3  </b></a>
          <ul style="display: none;">
             <li id="sub1"><a href="#url">inner1</a></li>
             <li id="sub2"><a href="#url">inner2</a></li> 
             <li id="sub3"><a href="#url">inner3</a></li>

         </ul>
    </li>

    <li id="outer4m"><a href="#url"><b class="">outer4</b></a>
           <ul style="display: none;">  
            <li id="sub8"><a href="#url"><i class="">inner4 </i></a></li>
            <li id="sub9"><a href="#url"><i class=""> inner5</i></a></li>
            </ul>
    </li>
</ul>


   My code.
         $("li ").click(function()
          { 
                if($(this).is("[id ^='sub']")){ 
                      var current_id=$(this).attr('id'); 
                      alert(current_id);
                }

         });

This code helps to alert inner list like sub1,sub2..etc during click. How to alert the Outer IDS? on click .When I Tried to check the above code to Outer It also alerts ths sub ID name. Can you suggest the optimized Procedure.

A: 
var parent_id=$(this).parent().parent().attr('id');

It's ugly, but the only way I know of that will traverse up the tree.

John Sheehan
A: 

What you want to do is traverse up the parent() tree to the very last one -- here's how I would do that:

$("li").click(function(){
    if($(this).is("[id^='sub']")){
     var all_ul_parents = [];
     // get parents which are uls, and put each id in an array
     $(this).parents().filter('ul').each(function(){
      all_ul_parents.push($(this).attr('id'));
     });
     // the final one added will be highest level ul parent
     current_id = all_ul_parents.pop();
     alert(current_id);
    } 
});
artlung
+1  A: 

try

$(this).parents('ul:last').attr('id')
redsquare
This gives nav as result. onclick of 'outer1m' i need to extract clicked ID
venkatachalam