innerHTML and innerText Properties

calendar November 16, 2009

Value: String

Compatibility: WinIE4+, MacIE4+, Moz1+, Safari1+

The innerHTML property contains not only the text content for an element , but also every bit of HTML tagging that is associated with that content. The browser interprets any HTML tags that you include in a string you assign to an element’s innerHTML property as tags. This also means that you can introduce entirely new nested elements.

The innerText property knows only about the text content of an element container, if you assign a string to the innerText property of an element and that string contains HTML tags , the tags and their angle brackets  appear in the rendered page and are interpreted as live tags.

Do not modify the innerHTML property to adjust the HTML for frameset, html, head and title objects.

Code:

<html>
<head>
<title>innerHTML and innerText properties</title>
<style type="text/css">
h1 {font-size:18pt;font-weight:bold;font-family:Comic Sans MS,Arial sans-serif}
.small {font-size:12pt;font-weight:400;color:gray}
</style>
<script type="text/javascript">
function setText(form)
{
  var content = form.textInput.value;
  if(content)
  {
    document.getElementById("label").innerText = content;
  }
}
function setHTML(form)
{
  var content = form.HTMLInput.value;
  if(content)
  {
    document.getElementById("label").innerHTML = content;
  }
}
</script>
</head>
<body>
<form>
<p>
<input type="text" name="HTMLInput"
value="&lt;I&gt;First&lt;/I&gt; Article &lt;span class='small'&gt;(of ten)&lt;/span&gt;" size="50" />
<input type="button" value="Change HTML" onclick="setHTML(this.form)"/>
</p>
<p>
<input type="text" name="textInput"
value="&lt;I&gt;First&lt;/I&gt; Article &lt;span class='small'&gt;(of ten)&lt;/span&gt;" size="50" />
<input type="button" value="Change Text" onclick="setText(this.form)"/>
</p>
</form>
<h1 id="label">Article 1</h1>
<p>Add these eight nutritional powerhouses to your diet to help you look and feel youthful.</p>
</body>
</html>

Related items: outerHTML, outerText properties, replaceNode( ) method.

admin

Leave a Reply

You must be logged in to post a comment.