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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.