The innerHTML property supplies read/write access to the entire contents of nearly any HTML element with descendants. This means you can retrieve, alter, and reset the contents of HTML elements within the body, and also the contents of an entire HTML document! The link below fires an alert box displaying as a string, all descendants of this document's html tag.
Begin typing HTML/plain text in the Textarea:
(Backspace to delete)
You can also...
Note: The HTML you retrieve via innerHTML is rendered HTML (parsed by browser).
The code sample below is the basis for the working example; more functionality was added to the working example to give you some ideas.
<div id="myDivElm"></div>
<form>
<textarea id="tArea">
</textarea>
<input type="button" value="Set innerHTML"
onclick="document.getElementById('myDivElm').innerHTML = document.getElementById('tArea').value">
<!-- the property "value" is used instead of "innerHTML" when the object is a form element -->
</form>
I've been asked how to write an HTML anchor (link) to a textarea; textareas are intended to display plain text, not functioning HTML. You CAN write to any block level or inline element, such as the DIV element in the example, using innerHTML.
Using the Visibility Property to Hide and Show HTML Elements
Making an element visible or hidden is as simple as setting it's visibility attribute to "hidden" or "visible". The default setting is visible. Follow the path to the property via the style object.
document.getElementById("myDivID").style.visibility = "hidden";
// makes the div hidden
document.getElementById("myDivID").style.visibility = "visible";
// makes the div visibile
Hi! I'm Green.
Using innerHTML to Add and Remove HTML
Notice how hiding an element affects (or doesn't affect) the content around it. Surrounding content will stay put because the newly hidden content is still there - it's just not visible. This may or may not be your desired result. If you want to shrink surrounding content, you'll have to remove the contents you want hidden altogether. You can do this with innerHTML.
document.getElementById("myDivID").innerHTML = "";
// sets all contents to an empty string
Store the html contents of the div in a variable before setting it to an empty string, if you will need it later.
var contentHolder = document.getElementById("myDivID").innerHTML;
// puts html contents of div in variable for later use
document.getElementById("myDivID").innerHTML = "";
// sets all contents to an empty string
Now when you hide the green element, the content surrounding it fills in the empty area with existing content.