innerHTML

innerHTML is a property you can access like .style and img's .src and what it represents is "what's between the tags." You can even insert elements, and not just text. Remember that if you assign something, the old value will be overwritten, though a little use of string concatenation can keep the old contents around. This wasn't very standard originally but it is much easier than manipulating the DOM tree. Note that innerHTML is not a function so you shouldn't use parentheses.

Examples:

Basic Usage

The Code
<h2 id='AnH2' onclick="this.innerHTML=prompt('What Should I say?')">____________</h2>
<button onclick="document.getElementById('AnH2').innerHTML='____________';">Reset &lt;h2&gt;</button>
Click the <h2>

____________




Appending content

The Code
<button onclick="this.innerHTML=this.innerHTML+'!';">Click if you're excited</h1>
Click button to execute:



Changing Different elements and same with Function

The code
<script type="text/javascript">
function graffiti(obj){
obj.innerHTML="jAm3s wu2 her3";
}
</script>
<h1 id="sign">Limited time offer! Two for one....</h1>
<button onclick="graffiti(this);graffiti(document.getElementById('sign'))">Graffiti</button>
Click button to execute:

Limited time offer! Two for one....



Inserting elements (also appending)

The Code
<p id="gburg">Four score and seven years....our forefathers....</p>
<button onclick="document.getElementById('gburg').innerHTML=
document.getElementById('gburg').innerHTML+
'<a href=\'http://en.wikipedia.org/wiki/Gettysburg_Address\'>Wikipedia</a>';">
Show Source
</button>
Click button to execute:

Four score and seven years....our forefathers....






Back to Knowledge Dump