Reputation: 939
Here, why jQuery closest
isn't working ? I've tried using find
, next
but doesn't work. I want to add html
only in closest class
of li
which contains children
ul
.
$(document).ready(function(){
if ($('li').children("ul").length) {
$(this).closest(".submenu").html('+');
}
})
*{
margin:0px;
padding:0px;
}
ul li{
list-style:none;
float:left;
margin-right:10px;
}
ul li ul li{
float:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<ul>
<li>General<span class="submenu"></span></li>
<li>Extra<span class="submenu"></span></li>
<li>Sport<span class="submenu"></span>
<ul>
<li>
Volleyball
</li>
<li>
Football
</li>
</ul>
</li>
</ul>
</body>
</html>
Upvotes: 0
Views: 62
Reputation: 473
You can do that in the easiest way by changing the code from
if ($('li').children("ul").length) {
$(this).find('span').html('+');
}
to this
$('ul li:has(ul)').find(".submenu").html('+');
$(document).ready(function(){
$('ul li:has(ul)').find(".submenu").html('+');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>General<span class="submenu"></span></li>
<li>Extra<span class="submenu"></span></li>
<li>Sport<span class="submenu"></span>
<ul>
<li>
Volleyball
</li>
<li>
Football
</li>
</ul>
</li>
</ul>
Upvotes: 1
Reputation: 7970
You need to find the length of ul
which is inside the li
.
$('.submenu').parent().each(function(){
if ($(this).children("ul").length) {
$(this).find('.submenu').html('+');
}
})
*{
margin:0px;
padding:0px;
}
ul li{
list-style:none;
float:left;
margin-right:10px;
}
ul li ul li{
float:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<ul>
<li>General<span class="submenu"></span></li>
<li>Extra<span class="submenu"></span></li>
<li>Sport<span class="submenu"></span>
<ul>
<li>
Volleyball
</li>
<li>
Football
</li>
</ul>
</li>
</ul>
</body>
</html>
Upvotes: 2