Reputation: 730
My html code
<ul id = "1">
<li>elti</li>
<li></li>
<li></li>
<li></li>
</ul>
to delete the empty li I'm using the below javascript code:
var y = document.getElementById("1");
x = y.getElementsByTagName("li");
for( i = 0; i < x.length ; i++) {
if (x[i].innerHTML === "" ){
y.removeChild(x[i]);
}
}
but the output is this:
<li>elti</li>
<li></li>
as you can see it doesn't delete a li tag. What am I doing wrong?
Upvotes: 2
Views: 221
Reputation: 36438
Work in reverse; else when you delete an item, you skip the check of the next item in the list:
for( i = x.length - 1; i >= 0; i--) {
if (x[i].innerHTML === "" ){
y.removeChild(x[i]);
}
}
var y = document.getElementById("1");
x = y.getElementsByTagName("li");
for( i = x.length - 1; i >= 0; i--) {
if (x[i].innerHTML === "" ){
y.removeChild(x[i]);
}
}
<ul id = "1">
<li>elti</li>
<li></li>
<li></li>
<li></li>
</ul>
Upvotes: 4