elti musa
elti musa

Reputation: 730

How to delete all <li> with innerHTML = = "";

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

Answers (1)

Paul Roub
Paul Roub

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

Related Questions