简体   繁体   中英

jQuery: Select all parents of the selected LI element

I have a hierarchical UL list. How to - using jQuery - get the all parents of the selected LI element and change the <a> 's background color inside each parent ?

<ul id="nav">
    <li>
        <a href="#">A</a>
        <ul>
            <li>
                <a href="#">B</a>
                <ul>
                    <li><a href="#">B1</a></li>
                    <li><a href="#">B2</a></li>
                    <li><a href="#">B3</a></li>

                    <li><a href="#">B4</a></li>
                    <li><a href="#">B5</a></li>
                </ul>
            </li>
            <li>
                <a href="#">C</a>
                <ul>
                    <li><a href="#">C1</a></li>
                    <li><a href="#">C2</a></li>
                    <li><a href="#">C3</a></li>
                </ul>
            </li>
        </ul>

If I eg select <a href="#">B4</a> , <a href="#">B</a> and <a href="#">A</a> will be also selected

The following will bind a click event to all <li> elements, and literally apply a background color to all parents and itself.

$('li').click(function() {
    $(this).parents().andSelf().css('background-color', 'red');
});

jQuery docs:

假设A和B都是UL元素,则以下代码应该起作用:

$(this).parents('ul').addClass('new_class');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM