开发者

jquery selector - choosing parents but not children

开发者 https://www.devze.com 2023-04-01 13:16 出处:网络
I am trying to use jquery to select an element and add a class to that element. My html is similar to the following:

I am trying to use jquery to select an element and add a class to that element. My html is similar to the following:

<ul id="top">
    <li class="menu-item menu-item-type-post_type menu-item-object-page current-menu-ancestor current-menu-parent current_page_parent current_page_ancestor">
    <a href="#">Corporate</a>
        <ul class="sub-menu">
            <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-11">
                <a href="#">Press</a>
            </li>
            <li class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-88 current_page_item menu-item-90">
                <a href="#">Press</a>
            </li>
        </ul>
    </li>
    <li><a href="#"></a></li>
    <li><a href="#"></a></li>
    <li><a href="#"></a></li>
    <li><a href="#"></a>
         <ul class="sub-menu"><li><a href="#">Link</a></li></ul>
    </li>
</ul>

I would like to add a class of "arrow" to every anchor link that is a direct child of the first-level <li> elements. In other words, I would like the "corporate" link to have a class of "arrow" but not any of the anchor links within .submenu to have that class. I have tried the following jquery ($("li.current_page_ancestor a:nth-child(1)").addClass("arrow");), bu开发者_Python百科t it adds the class to every anchor link, which makes sense. How do I just add that class to the anchor links that are a direct child of the top-level list items?


> is the child selector:

$('li.current_page_ancestor > a').
  add($('.sub-menu').parent().children('a')).
    addClass('arrow');


Like this?

$('ul#top > li > a').addClass('arrow')

The css-selector " > " means "direct decedent", or "direct child".

0

精彩评论

暂无评论...
验证码 换一张
取 消