JavaScript to Empty Something
-
In my tutorial I've this little loop:
while ( div.hasChildNodes() ) { // empty the div div.removeChild( div.firstChild );This works, but is it just the hard way to do this:
div.innerHTML = ''?
-
Completely different things, no? One is removing child nodes from a container element, the other is setting the value of a property of an element.
-
They are the same:
<html><body> <h1> Headline </h1> <button onclick='dump1()'> Dump1 </button> <button onclick='dump2()'> Dump2 </button> <script> function dump1() { alert( document.body.hasChildNodes() ); document.body.innerHTML = ''; alert( document.body.hasChildNodes() ); } function dump2() { alert( document.body.innerHTML ); while ( document.body.hasChildNodes() ) { document.body.removeChild( document.body.firstChild ); } alert( '[' + document.body.innerHTML + ']' ); } </script> </body></html> -
The former used to be the W3C standard way. The latter used to be the non-standard. But as of HTML5 I believe
innerHTMLandouterHTMLare now standard.
Pretty well supported anyway.
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better π
Register LoginAdvertisement