轉自 https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
--
The insertAdjacentHTML() method 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 innerHTMLmanipulation.
SyntaxSection
element.insertAdjacentHTML(position, text);
ParametersSection
position- A
DOMStringrepresenting the position relative to theelement; must be one of the following strings:'beforebegin': Before theelementitself.'afterbegin': Just inside theelement, before its first child.'beforeend': Just inside theelement, after its last child.'afterend': After theelementitself.
texttextis the string to be parsed as HTML or XML and inserted into the tree.
Visualization of position namesSection
<!-- 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.ExampleSection
// <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>
NotesSection
Security ConsiderationsSection
When inserting HTML into a page by using insertAdjacentHTML be careful not to use user input that hasn't been escaped.
It is not recommended you use insertAdjacentHTML when inserting plain text; instead, use the Node.textContent property or Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.
SpecificationSection
| Specification | Status | Comment |
|---|---|---|
| DOM Parsing and Serialization The definition of 'Element.insertAdjacentHTML()' in that specification. |
Working Draft |
Browser compatibilitySection
| Desktop | Mobile | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Full support1 | Full support12 | Full support8 | Full support4
Notes
Open |
Full support7 | Full support4 | Full support2.3 | Full support18 | Full support12 | Full support8 | Full supportYes | Full support4 | Full supportYes |
Legend
- Full support
- Full support
- See implementation notes.
- See implementation notes.
See alsoSection
Element.insertAdjacentElement()Element.insertAdjacentText()XMLSerializer: Construct a DOM representation of XML text- hacks.mozilla.org guest post by Henri Sivonen including benchmark showing that insertAdjacentHTML can be way faster in some cases.
Document Tags and Contributors
--
