How do I use jquery to select a sibling of the parent element?

旧巷老猫 提交于 2019-12-24 09:25:19

问题


I am trying to use jquery to specifically select a sibling a parent element that has the same . the code is like this:

HTML

    <div class="cool-check-list">
        <ul>
        <li>
            <label>
                <span class="icon"></span> <!-- trying to select this -->
                Awesome Label Name
            </label>

            <ul>
                <li>
                    <label>
                        <span class="icon"></span> <!-- clicking this toggles the class of the above icon class -->
                        Awesome Label Name 2
                    </label>    
                </li>                        
            </ul>
        </li>
        </ul>
   </div>

JQUERY

    $('.icon', '.cool-check-list').click( function(e){

    $(this).parent('li label .icon').toggleClass('icon-alternate');

    });

回答1:


Assuming you've already gotten a reference to the clicked span, you could do this:

$(this).closest("ul").siblings().find(".icon")

Where this is the span you clicked. closest gets the nearest ancestor that matches the selector.




回答2:


You should tell us more precisely what you wanted to select and what you tried.

Anyway, you can use the parents() function of jquery, for instance :

$(".icon").parents("li")

will select every node li 'before' the class icon in the DOM.

Btw, take care of the difference between parents and parent - quoting the jquery documentation:

The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.



来源:https://stackoverflow.com/questions/6455436/how-do-i-use-jquery-to-select-a-sibling-of-the-parent-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!