Summary
insertAdjacentHTML()
parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML
manipulation.
Syntax
element.insertAdjacentHTML(position, text);
position
is the position relative to the element
, and must be one of the following strings:
'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.
text
is the string to be parsed as HTML or XML and inserted into the tree.
Visualization of position names
<!--beforebegin
--><p>
<!--afterbegin
--> foo <!--beforeend
--></p>
<!--afterend
-->
Note: The
beforebegin
and afterend
positions work only if the node is in a tree and has an element parent.Example
// <div id="one">one</div> var d1 = document.getElementById('one'); d1.insertAdjacentHTML('afterend', '<div id="two">two</div>'); // At this point, the new structure is: // <div id="one">one</div><div id="two">two</div>
Specification
Specification | Status | Comment |
---|---|---|
DOM Parsing and Serialization The definition of 'Element.insertAdjacentHTML()' in that specification. |
Working Draft |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | 1.0 | 8.0 (8.0) | 4.0 | 7.0 | 4.0 (527) |
Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | ? | 8.0 (8.0) | ? | ? | ? |
See also
Node.insertBefore()
Node.appendChild()
(same effect asbeforeend
)- hacks.mozilla.org guest post by Henri Sivonen including benchmark showing that insertAdjacentHTML can be way faster in some cases.
Document Tags and Contributors
Tags:
Contributors to this page:
hibiya,
cvrebert,
Sheepy,
romain-lebesle,
upq,
marcel-burkhard,
chrisdavidmills,
lee_elenbaas,
fscholz,
teoli,
kscarfone,
vishu_gawli,
LouisLazaris,
dbruant,
Sheppy,
mattbasta,
ethertank,
Rob W,
tehsis,
Marcoos,
berkerpeksag,
BYK,
Hsivonen,
myakura,
trevorh
Last updated by:
hibiya,