2

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?

Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
elti musa
  • 590
  • 2
  • 6
  • 14
  • 1
    Your `x` is going to keep changing as you remove elements from it. After a few iterations, `x[i]` is no longer going to be what you think it is. – Rocket Hazmat Oct 29 '14 at 20:30
  • ID attributes must start with a letter (http://www.w3.org/TR/html401/types.html#type-name) – jeff Oct 29 '14 at 20:32
  • 1
    @jeff Numeric IDs are valid in HTML 5. http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Paul Roub Oct 29 '14 at 20:33

1 Answers1

4

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>
Paul Roub
  • 35,100
  • 27
  • 72
  • 83
  • 3
    +1 This is because when you delete an element, all indexes move 1 to the left, but your `i` iteration variable doesn't account for it – slezica Oct 29 '14 at 20:30
  • This is correct. He could also just decrement his index when he removes an element `y.removeChild(x[i--]);` – bitwiser Oct 29 '14 at 20:35