Wednesday, April 22, 2009

Targeting Nested LI's with jQuery

After two days of trying every DOM hierarchy transversile that I could think of or learn from I was about to give up. The task at hand was fairly simple. I was creating a TreeView menu for a given directory. The top level nodes where generated when the page loads and if the top level "resource" is a directory then when that item is clicked an AJAX call is made to get it's sub-resources which are nested ul/li.

In order to make subsequent calls for any directories/files that are > the first level I need to get the id of the li tag that is clicked (only directories have the ability to be clicked).

I thought I would be able to navigate through the DOM hiearchy to the nested li and retrieve the id, however, this becomes a problem with nested ul/li's because if you try to alert the id and expect the result to be of the nested element you will get the id of the parent element.

List Items


  • [+]applications


    • lib
    • index.php
    • settings
    • .htaccess
    • images
    • css
    • views
    • js
    • modules
    • layouts
  • [+]ops

// doesn't work

$(document).ready(function() {

$("li").click(function() {
alert($(this).attr('id'));

})
});


// does work
$(document).ready(function() {

$("li").click(function(event) {
alert(event.target.id);

})
});


The solution was to pass and event object to the click event handler. After I figured out that little nugget it only took me another hour to finish up my script.

No comments: