Question : Jquery Traversing

Hi Guys

Im trying to make a function that if i click on the span SEARCH then it should alert the text SEARCH but also CUSTOMERS. how do i do that? Nothing i do seems to work

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tracker</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel='stylesheet' type='text/css' media='screen' href='/include/jquery.treeview.css'>
<script type="text/javascript" src="/include/jquery-1.4.2.min.js"></SCRIPT>
<script type='text/javascript'>
    $(function () {
        $("#treemenu span").each(function () {
            //var parentTxt = $(this).parent('li').parent('ul').parent('li,span').text();
            $(this).click(function () {
                var clickedTxt = $(this).text();
                var parentTxt = $(this).parent('span.folder').text();
                load(clickedTxt, parentTxt);
            });
        });
        function load(val1, val2) {
            alert("val1=" + val1 + "\nval2=" + val2);

            //dumpProps(val2);
        }
    });

</script>
</head>
<body>
<ul id="treemenu" class="filetree">
      <li><span class="folder">Customers</span>
            <ul id='test'>
                  <li><span style=''>Search</span></li>
            </ul>
      </li>
</ul>
</body>
</html>

Answer : Jquery Traversing

Instead of:
    var parentTxt = $(this).parent('span.folder').text();

use:
 var parentTxt = $('span.folder', $(this).closest("ul").parent() ).text();

which basically states:
look for span.folder WITHIN $(this).closest("ul").parent().

If you take a closer look at your markup, it should be clear that when you click on Search, $(this).closest("ul") refers to <ul id="test"> and its parent is the li that contains both, <ul id="test"> AND <span class="folder">.

So essentially this:
$(this).closest("ul").parent()

refers to the first <li> in <ul id="treemenu">. So, to summarize:

$('span.folder', $(this).closest("ul").parent() ).text();
says:
look for span.folder within the li in <ul id="treemenu">
Clear?
Random Solutions  
 
programming4us programming4us