views:

34

answers:

3

i have a tree structure,there is an unordered list(ul) in that tree.i have li items in it,and in that li items it could be a span or an ul list.

this is one part of my codes :

            <li id="main_li">
                <div class="first_division"></div>
                <span>products</span>
                <ul style="display: block;">
                    <li>
                        <div class="division1"></div>
                        <span>products_cat_1</span>
                        <ul style="display: none;"> 
                            <li>
                                <span>products_cat_1_milk</span>
                            </li>
                        </ul>
                    </li>                   
                    <li>
                        <span>products_yoghurt</span>
                    </li>                   
                    <li>
                        <span>products_butter</span>
                    </li>
                </ul>
            </li>

i want to access li elements in ul tag where the parent li id is "main_li",i want to get it done by clicking on the span within li.

how can i do this with jquery?

+1  A: 

The CSS selector that matches the li elements under uls whose parent is 'main_li' is

#main_li > ul > li

further to comment below:

To access the ul that is a sibling to a span, you want the next() selector. If you're in a click handler on the span, the span will be this:

var siblingUL = $(this).next('ul');
DDaviesBrackett
i want to get li elements in ul which its parent li is clicked.i mean when i click on "products_cat_1",how can i access to "products_cat_1_milk" with jquery?
armin etemadi
+1  A: 

Attach a click handler to the relevant <span>. Inside the handler function, navigate to the nodes of interest using tree traversal methods.

Some selectors that might be useful here:

[X] > [Y] // select all Y that are children of X
[X] [Y]   // select all Y that are descendants of X

Example)

$("#main_li > span")
// selects:
// <span>products</span>

$("#main_li span")   
// selects:
// <span>products</span>
// <span>products_cat_1</span>
// <span>products_cat_1_milk</span>
// <span>products_yoghurt</span>
// <span>products_butter</span>

Assuming you attach a click handler on <span>products</span>, and inside the click handler you want to navigate to all <li> children that are at the same level as this span, you could do:

$("#main_li > span").click(function() {
    $(this).siblings("ul").children("li").each(function() {
        // do something with each <li>
    });
});
Anurag
thank you so much buddy,my problem is solved by your recomendation:)really thanks
armin etemadi
You're welcome, glad it helped. Cheers!
Anurag
A: 

If you have multiple LIs', you should use aclassrather thanideg#main_li`

$(function(){
  $('.main_li span').click(function(){
    $(this).parents('.main_li').find('li').each(function(){
      // your further code here....
    });
  });
});
Sarfraz