admin管理员组文章数量:1320822
I have a dropdown menu and I want to verify if the submenu hasClass in
, then for the closest ul
that has class .menu
add class in
. Here is my code but it adds for all ul
that has class .menu
instead closest.
<script>
if($(".submenu").hasClass( "in" )) {
$(".submenu").closest(".menu").addClass("in");
}
</script>
I have a dropdown menu and I want to verify if the submenu hasClass in
, then for the closest ul
that has class .menu
add class in
. Here is my code but it adds for all ul
that has class .menu
instead closest.
<script>
if($(".submenu").hasClass( "in" )) {
$(".submenu").closest(".menu").addClass("in");
}
</script>
Share
Improve this question
edited May 18, 2017 at 19:08
max
8,6873 gold badges25 silver badges56 bronze badges
asked May 18, 2017 at 19:05
chris227chris227
60711 silver badges32 bronze badges
5
- Please post your HTML as well – j08691 Commented May 18, 2017 at 19:07
- can you share html as well – Kiran Commented May 18, 2017 at 19:07
-
closest
finds the closest parent. Edit: oops, I misread! – Frank Modica Commented May 18, 2017 at 19:07 -
1
@FrankModica
.closest()
searches up the DOM through all ancestors of a given element, not just the parent – j08691 Commented May 18, 2017 at 19:08 - @j08691 and the element itself. – max Commented May 18, 2017 at 19:09
3 Answers
Reset to default 6You need to change the selector
$(".submenu.in").closest(".menu").addClass("in");
Alternatively :has()
selector can also be used as
Selects elements that contain at least one element that matches the specified selector.
$(".menu:has(.submenu.in)").addClass("in");
Try this:
For looking up the DOM use this:
<script>
$('.submenu.in').closest('.menu').addClass("in");
</script>
For looking into the children elements use this:
<script>
$('.submenu.in .menu').first().addClass("in");
</script>
I'm assuming you want to target a child element of .submenu
so try this
<script>
if($(".submenu").hasClass( "in" )) {
$(".submenu").children(".menu").addClass("in");
}
</script>
Or if you just want first level children here's a solution: How to select only the first level children in JQuery
本文标签: javascripthow to addClass to closest elementStack Overflow
版权声明:本文标题:javascript - how to addClass to closest element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742089753a2420192.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论