Removing all children from an element works when using getLastChild (), but throws a NullPointerException when using getFirstChild ()

I use GWT, and I have to manipulate the DOM directly because of a buggy widget that does not center itself properly. I wrote the following code to clear children in the <body> element while viewing transit, because RootPanel.clear () does not completely clear the HTML:

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

But it throws a NullPointerException. However, just changing getFirstChild() to getLastChild() works fine.

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

Any ideas why?

+4
source share
1 answer

When you delete the first child, the first child is now null. the second child is what you will need to remove now instead of the first and so on. So the call to getFirstChild returns you zero and you will see NPE. That is not the case with getLastChild.

+1
source

Source: https://habr.com/ru/post/1346770/


All Articles