var element = document.getElementById( “somediv” )
Recall that “var” means variable. Basically, what I’m doing here is saving a pointer to an element in the document with the id “somediv”. The only thing in our document with that ID should be the division I presented above.
We access the interior HMTL of the division by simply tacking on “innerHTML”. Save a string to this to change the interior HTML. It could look something like this:
document.getElementById( “somediv” ).innerHTML = “<p>New paragraph</p>”;
element.innerHTML = “<p>New paragraph</p>”;
Within this division, or any HTML tag, are something called “child nodes”. For all intensive purposes, these are other tags. We edit these almost exactly the same way as the division (because they also have an element called “innerHMTL”). The only difference is that we have to add childNodes[ childNumber ] between the “getElementByID(…)” and the “innerHTML”.
Do note that when you are saving to the innerHTML, if you have a quotation mark inside of your HTML text, you need to precede it by a slash ( \ ) so that the browser knows it belongs in the string (as opposed to terminating it).
I’ve provided an example below, and you can try it out on JSFiddle: (Note: this is not the end of the post)
var elem = document.createElement( “div” );
elem.innerHTML = “NOT!”;
document.getElementById( “area” ).appendChild( elem );
document.getElementById( “area” ).innerHTML = restore();
//document.getElementById( “area” ).childNodes.innerHTML = “”;
var newHTML =
“<button onclick=\”start()\”>Punch this</button><button onclick=\”reset()\”>Reset</button> “;
<button onclick=”start()”>Punch this</button>
But wait, there’s more!
Suppose we don’t want to type out everything in one line when we want to add it. In that case, it’s easy to just append to the document. You’ll find how to do that here, but the gist is this, utilizing the division I wrote up at the start of this article:
var element = document.createElement( “p” );
element.innerHTML = “Hello world”;
document.getElementById( “somediv” ).append( element );
Or you can remove the element via:
document.getElementById( “somediv” ).removeChild( element );