65 out of 152 rated this helpful - Rate this topic

innerHTML property

[This documentation is preliminary and is subject to change.]

Sets or retrieves the HTML between the start and end tags of the object.

Syntax

JavaScript

p = object.innerHTML

Property values

Type: String

the content between the start and end tags.

Remarks

The innerHTML property is valid for both block and inline elements. By definition, elements that do not have both an opening and closing tag cannot have an innerHTML property.

The innerHTML property takes a string that specifies a valid combination of text and elements. When the innerHTML property is set, the given string completely replaces the existing content of the object. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

This property is accessible at run time as the document is being parsed; however, removing elements at run time, before the document is fully loaded, could prevent other areas of the document from rendering.

When using innerHTML to insert script, you must include the DEFER attribute in the script element.

The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.

You can change the value of the title element using the document.title property.

To change the contents of the table, tFoot, tHead, and tr elements, use the table object model described in Building Tables Dynamically. However, to change the content of a particular cell, you can use innerHTML.

Security Warning:   Improper handling of the innerHTML property can enable script-injection attacks. When accepting text from an untrusted source (such as the query string of a URL), use createTextNode to convert the HTML to text, and append the element to the document using appendChild. Refer to the Examples section below for more information.

To maintain compatibility with earlier versions of Windows Internet Explorer, this property applies to the textArea object. However, the property works only with strings that do not contain tags. With a string that contains a tag, this property returns an error. It is better to use the innerText property with this object.

Examples

This example uses the innerHTML property to change the text of a paragraph when an onmouseover event occurs. The affected text and any tags within it are changed by the onmouseover and onmouseout events.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/innerHTML.htm


...
<P onmouseover="this.innerHTML='<B>Mouse out to change back.</B>'"
    onmouseout="this.innerHTML='<I>Mouse over again to change.</I>'">
    <I>Mouse over this text to change it.</I>
</P>
...

This example uses the innerHTML property to insert script into the page.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/insertScript_2.htm


<HTML>
<SCRIPT>
function insertScript(){
    var sHTML="<input type=button onclick=" + "go2()" + " value='Click Me'><BR>";
    var sScript="<SCRIPT DEFER>";
    sScript = sScript + "function go2(){ alert('Hello from inserted script.') }";
    sScript = sScript + "</SCRIPT" + ">";
    ScriptDiv.innerHTML = sHTML + sScript;
}    
</SCRIPT>
<BODY onload="insertScript();">
    <DIV ID="ScriptDiv"></DIV>
</BODY>
</HTML>

The following example demonstrates how to convert the HTML source to text using a temporary div element and createTextNode. Once the HTML is sanitized, it can be safely inserted into the document using innerHTML.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/innerHTMLsafe.htm


<body onload="displaySource()">

<script type="text/javascript">
function sanitizeHTML(s) {
    var d = document.createElement('div');
    d.appendChild(document.createTextNode(s));
    return d.innerHTML;
}

function displaySource()
{
    var h = sanitizeHTML(document.documentElement.outerHTML);
    document.getElementById('asHTML').innerHTML = "<pre>" + h + "</pre>";
    document.getElementById('asText').innerText = h;
}
</script>

<h2>As HTML</h2>
<div id="asHTML"></div>
<h2>As Text</h2>
<div id="asText"></div>

</body>


See also

a
abbr
acronym
address
applet
area
article
aside
b
bdo
big
blockQuote
body
br
button
caption
center
cite
code
col
colGroup
custom
dd
del
dfn
dir
div
dl
dt
em
embed
fieldSet
figcaption
figure
font
footer
form
frame
frameSet
head
header
hgroup
hn
hr
html
i
iframe
img
input type=button
input type=checkbox
input type=file
input type=hidden
input type=image
input type=password
input type=radio
input type=reset
input type=submit
input type=text
ins
isIndex
kbd
label
legend
li
listing
map
mark
marquee
menu
nav
nextID
noBR
object
ol
optGroup
option
p
plainText
pre
q
rt
ruby
s
samp
section
select
small
span
strike
strong
sub
sup
table
tBody
td
textArea
tFoot
th
tHead
tr
tt
u
ul
var
xmp
Reference
insertAdjacentHTML
Conceptual
Building Tables Dynamically

 

 

Build date: 3/8/2012

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
innerHTML not reflecting element's value change in IE9 Standards Mode
I have javascript that takes the innerHTML of a DIV and appends new html to it.  The problem I'm having is that when I read the innerHTML, it is out of date with what is on the page.  When a user changes the value of an input element, it isn't being updated in the innerHTML.  Problem occurs in IE9 Standards mode, but not in IE8 standards mode.
textarea.innerHTML error
when i want to change the style of text in the textarea by below code, it gives me  htmlfile: Unknown runtime error , what can i do ? why does it give me a such this error ? $0$0 $0 $0document.getElementById('area').innerHTML = "<b>display 1 was selected<\/b>";$0 $0$0 $0 $0$0 $0 $0thanks.$0
Is <script> also read only?
I ran into this issue trying to replace text within a <script> for client side templating. Is <script> also read only?
trying to use HTML5 <video> tag in innerHTML
Can you specify HTML5 <video> tag when using innerHTML? This is what I am trying to do.

<script type="text/Javascript">
function insertPlayList()
{

ScriptDiv.innerHTML = '<video width="512" height="320" controls="controls" autoplay="autoplay"> <source src="address of the location of my video" type="video/mp4" /> </video>';
}
</script>


</head>
<body onload="insertPlayList()">
<div id="ScriptDiv">
</div>

</body>
</html>

this doesn't seem to work. anybody know why? seems like it doesn't know or get the src address of the video stream. All I get is a black box but in the correct width/height location.
However, if I copy and paste the whole video tag (<vidieo width="512"....) in between the <div> tag, this works perfectly. The video would load and when I press play, the video plays.

I notice that from the innerHTML description, it doesn't list "video" as one of the tags that it supports. Is that true? is that why what I am trying to do does not work?

any input or response would help.
thanks
  • 7/24/2010
  • ccx
Converting InnerHTML to XHTML
HI,

Here is a code for converting the InnerHTML to XHTML. Now these days we are mostly bind to XHTML format. so there are many times we may requires to convert the HTML to XHTML

I have explained this in my blog.. please read on

http://tech-buds.blogspot.com/2009/12/convert-innerhtml-to-xhtml.html

Shidhin
InnerHTML distorts original document

HI,

I have used div tag to render xhtml document using innerHTML property. But unfortunately innerHTML modifies my document by changing the tags(e.g <TBODY> will be added after <TABLE>). For my requirement it is totally unacceptable since the document rendered using innerHTML will not be same as original document. Is there a way to avoid this. Render all the tags as it is of the original document but again using div tag and client side rendering. Any Help regarding this is very appreciable!

What constitutes valid innerHTML?
"The innerHTML property takes a string that specifies a valid combination of text and elements."
Internet Explorer is known for being strict in accepting certain constructs (table cells, for instance) as innerHTML. Other browsers seem to allow anything.
What constitutes "a valid combination of text and elements" when setting innerHTML?
Wonderful!

I am sure.. I understand this logic.

Wonderful working and very nice sharing Microsoft! I am using in http://www.atasozlerianlamlari.com web site.

Thank you very much!

Injected execution schedule
The deferred script is executed synchronously, as soon as it gets attached to the document.
What constitutes valid text

If the string ends with an ampersand "&" followed by up to ten alphanumeric characters, the ampersand and all following text is ignored (truncated).

re:something wrong???? bug????
@kangGaia
"The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR."
Don't rely on attribute order

As a side effect of changes in the attributes implementation, the order of attributes reported by innerHTML has changed significantly from IE 7 to IE 8. Here's a quick explanation from our developer team:

"At the time of the change we did some investigation and found that attributes order has changed to some degree with every new release of IE. Appearances of mostly alphabetic ordering have been accidental. While the jump between IE7 and 8 may have been bigger than previous changes, the order has never been 100% stable. For this reason the side effect was deemed acceptable."

SO, don't rely on a specific order when parsing HTML code returned by innerHTML. A better solution in any case would be to use attribute.specified to determine if a value has been set.

http://msdn.microsoft.com/en-us/library/ms534637(VS.85).aspx

How to inject NoScope elements into a page with innerHTML.

You can inject script with innerHTML, but it can be a little tricky. The example above works around this limitation, but doesn't really explain how it is done.

Internally, Internet Explorer treats the <script> tag as a NoScope element, which means (according to a rather opaque comment in the source) that "no text in a textrun should point to it." Examples of other tags that have this attribute are HTML comments (<!-- -->) and STYLE tags. All NoScope elements are removed from the beginning of the parsed HTML before it is injected with innerHTML or insertAdjacentHTML. To prevent this from happening, you must include at least one scoped element at the beginning of the injected HTML.

The following example injects a script block into the injectionDiv, but nothing happens.

<div id="injectionDiv">&nbsp;</div>
<script type="text/javascript">
injectionDiv.innerHTML='<script defer>alert("hello");</' + 'script>';
</script>

To make it work, you must start the injected HTML string with a scoped element, preferably an invisible one like a hidden input element.

injectionDiv.innerHTML='<input type="hidden"/><script defer>alert("hello");</' + 'script>';

Note The strange '</' + 'script>' construct prevents the real SCRIPT block from closing prematurely.

The same rules apply to injected STYLE elements. All we have to do is put the style block after the element it modifies.

injectionDiv.innerHTML='<div class="myClass">&nbsp;</div><style type="text/css">.myClass{background-color:green;}</style>';

That said, you really should put all style rules in the HEAD for strict compliance with XHTML. Doing this can also be a little tricky because you cannot use innerHTML to inject into the HEAD or STYLE element directly. (Both of these tags are READ ONLY.) The best way to dynamically add styles to a page is to wait for the document to load, and then create the rule in a new style sheet.

window.onload = function() 
{
document.createStyleSheet().addRule('.myClass', 'background-color:blue!important;');
}

Source: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=909379&SiteID=1