Reputation: 1725
With this given code below, I would like to remove any 'li' element whose child ol
element does contain any li
element, yet with no avail.
$(document).ready(function() {
$('#myUL li').each(function() {
var lenLi = $(this).find('ol').children('li').length;
if (lenLi == 0) {
$(this).remove();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ol id="myUL">
<li>Hello 1</li>
<li>Hello 2
<ol></ol>
</li>
<li>Hello 3
<ol>
<li>Hello 3.1</li>
<li>Hello 3.2</li>
<li>Hello 3.3</li>
</ol>
</li>
</ol>
after executing code above, Hello 1, Hello 2 were removed. However, children of Hello 3 were all removed as well.
My question is why was that?
Upvotes: 0
Views: 166
Reputation: 18975
You can use query selector #myUL li ol
for find ol and check li inside it.
$(document).ready(function() {
$('#myUL li ol').each(function() {
var lenLi = $(this).find('li').length;
console.log(lenLi);
if (lenLi == 0) {
$(this).remove();
}
})
})
$(document).ready(function() {
$('#myUL li ol').each(function() {
var lenLi = $(this).find('li').length;
console.log(lenLi);
if (lenLi == 0) {
$(this).remove();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ol id="myUL">
<li>Hello 1</li>
<li>Hello 2
<ol></ol>
</li>
<li>Hello 3
<ol>
<li>Hello 3.1</li>
<li>Hello 3.2</li>
<li>Hello 3.3</li>
</ol>
</li>
</ol>
Upvotes: 0
Reputation: 97672
Your selector #myUL li
is also selecting the li
s in Hello 3 because they are li
descendants of #myUL
and since they have no ol
with li
in them they get removed.
You can use the child selector >
to only select the children of #myUL
.
$(document).ready(function() {
$('#myUL > li').each(function() {
var lenLi = $(this).find('ol').children('li').length;
if (lenLi == 0) {
$(this).remove();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ol id="myUL">
<li>Hello 1</li>
<li>Hello 2
<ol></ol>
</li>
<li>Hello 3
<ol>
<li>Hello 3.1</li>
<li>Hello 3.2</li>
<li>Hello 3.3</li>
</ol>
</li>
</ol>
Upvotes: 3
Reputation: 44105
Your code is iterating through all li
contained within#myUL
. Use a first-level child selector >
:
$(document).ready(function() {
$('#myUL > li').each(function() {
var lenLi = $(this).find('ol').children('li').length;
if (lenLi == 0) {
$(this).remove();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ol id="myUL">
<li>Hello 1</li>
<li>Hello 2
<ol></ol>
</li>
<li>Hello 3
<ol>
<li>Hello 3.1</li>
<li>Hello 3.2</li>
<li>Hello 3.3</li>
</ol>
</li>
</ol>
Upvotes: 1
Reputation: 10237
if ($('#el').is(':empty')){
// custom code
}
More info here
Upvotes: 0