jquery选择器 - 选择父母而不是孩子
我正在尝试使用 jquery 选择一个元素并向该元素添加一个类。我的 html 类似于以下内容:
<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>
我想向作为第一级
元素的直接子级的每个锚链接添加“箭头”类。换句话说,我希望“公司”链接具有“箭头”类,但 .submenu 中的任何锚链接都不具有该类。我尝试过以下 jquery ($("li.current_page_ancestor a:nth-child(1)").addClass("arrow");
),但它将类添加到每个锚链接,这是有道理的。如何将该类添加到作为顶级列表项的直接子项的锚链接?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");
), but 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
>
是子选择器:>
is the child selector:像这样?
css 选择器“>”表示“直接继承人”或“直接子代”。
Like this?
The css-selector " > " means "direct decedent", or "direct child".