This page is Almost Ready

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

insertAdjacentHTML

Summary

Parses and inserts HTML code at or beyond the edges of an element within the document hierarchy.

Method of dom/Elementdom/Element

Syntax

 element.insertAdjacentHTML(where, html);

Parameters

where

Data-type
String

Where to insert the HTML text. Must be one of the following values:

ValueDescription
“beforebegin”Before the element itself.
“afterbegin”Just inside the element, before its first child.
“beforeend”Just inside the element, after its last child.
“afterend”After the element itself.

html

Data-type
String

Well-formed HTML code to insert. The string can be a combination of text and HTML tags.

Return Value

No return value

Examples

This example uses the insertAdjacentHTML method to insert script into the page.

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.insertAdjacentHTML("afterBegin",sHTML + sScript);

View live example

Usage

 Use this method to add HTML to the page before/after an element or at the beginning or at the end of an element.

Notes

  • In XML documents, this methods will fail if the html parameter is not well-formed, valid HTML.
  • This method will fail if “afterend” or “beforebegin” is used when the context is the root element of the document.
  • If the text contains HTML tags, the method parses and formats the text as it is inserted.

TODO: The notes below need to be verified.

  • You cannot insert text while the document is loading. Wait for the onload event to fire before attempting to call this method.
  • When using the insertAdjacentHTML method to insert script, you must include the DEFER attribute in the script element.

Related specifications

DOM Parsing and Serialization
Living Standard

See also

Related pages

Attributions