4

I'm using GWT and I have to manipulate the DOM directly because of a buggy widget that doesn't center itself properly. I wrote the following code to clean up the children on the <body> element during view transistions because RootPanel.clear() doesn't clean up HTML completely:

while (root.hasChildNodes()) {
    root.removeChild(root.getFirstChild());
}

But it throws a NullPointerException. However, simply changing getFirstChild() to getLastChild() works perfectly.

while (root.hasChildNodes()) {
    root.removeChild(root.getLastChild());
}

Any ideas why?

Travis Webb
  • 14,688
  • 7
  • 55
  • 109

1 Answers1

1

When you remove the first child, the first child now is null. the second child is what you will have to remove now instead of the first, and so on. So, calling the getFirstChild returns you a null and thats y u get to see the NPE. Thats not the case with the getLastChild.

Jai
  • 3,549
  • 3
  • 23
  • 31
  • yes, but once I remove child1, child2 is no longer child2, it becomes child1. – Travis Webb Apr 06 '11 at 14:57
  • Well, if that were the case, you wouldn't see the exception. Just read the value of getFirstChild() after you have removed the first one. Do you see a null? – Jai Apr 06 '11 at 21:34