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 that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.
element.insertAdjacentHTML(position, text);
position is the position relative to the element, and must be one of the following strings:
'beforebegin'element itself.'afterbegin'element, before its first child.'beforeend'element, after its last child.'afterend'element itself.text is the string to be parsed as HTML or XML and inserted into the tree.
<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->
beforebegin and afterend positions work only if the node is in the DOM tree and has a parent element.// <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> When inserting HTML into a page by using insertAdjacentHTML be careful not to use user input that hasn't been escaped.
It is recommended you not use insertAdjacentHTML when inserting plain text; instead, use the node.textContent property or node.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.
| Specification | Status | Comment |
|---|---|---|
| DOM Parsing and Serialization The definition of 'Element.insertAdjacentHTML()' in that specification. | Working Draft |
| 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) | ? | ? | ? |
Element.insertAdjacentElement()Element.insertAdjacentText()
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/element/insertAdjacentHTML