views:

106

answers:

2

I want walk back up the tree menu of a nested unordered list to the top most < li > and retrieve the "p_node" attribute using the toggle function of jquery. So, for example, when I click on "Annie" I want to retrieve the root li, which in her case is "mCat1" and extract the value for "p_node" to be used in the script. How can I accomplish this? Thanks for your help.

Here's the unordered list:

<ul id="nav>
  <li type="root" p_node="39">Cat 2
     <ul>
        <li><a>sub cat2</a></li>
     </ul>
  </li>
  <li type="root" p_node="40">mCat1
      <ul>
         <li>Subcat A
            <ul>
               <li>Subcat A.1
                  <ul>
                     <li><a>Annie</a></li>
                  </ul>
               </li>
            </ul>
          </li>
        </ul>
   </li>
 </ul>

Here's some of the jquery I've been trying. the selector is selecting the bottom most < li > that has an anchor tag:

$('#nav li:not(:has(li))>a').toggle(function() {
                   //show stuff
                   var parentEls = $(this).parents()
                   .map(function () { 
                  if( $(this).attr('type') == 'root')
                  {
                    var node = $(this).attr('p_node');
                    return node;
                  }
            });
           }, function() {
                   //close stuff
});
+3  A: 

Try this:

$(clickReceiver).parents("li:last").attr('p_node')
morgancodes
Brilliant! Works perfectly. Thank you for your help.
Ronedog
Isn't jquery nice? :)
morgancodes
jQ selectors *are* brilliant. They've managed to create a sort of "six degrees of separation" between every element on the DOM.
dclowd9901
+2  A: 
$('#nav li:not(:has(li))>a').toggle(function() {
    //show stuff
    var parentEls = $(this).closest('li[type=root]').attr('p_node');
}, function() {
    //close stuff
});
PetersenDidIt
This is rather dense, it would help if you explained what is going on here.
Sorpigal
It's not dense, he's trying to provide an answer using code from the question. If you extract out the important part, this answer does essentially the same thing as morgancodes's answer, except he's using closest instead of parents and more specifically targeting the `li` with `type=root` - `$(clickReceiver).closest('li[type=root]').attr('p_node');`
fudgey
thanks pertersendidit. This worked great too...appreciate your help.
Ronedog