Element.insertAdjacentHTML() - Web APIs 编辑
The insertAdjacentHTML()
method of the Element
interface 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.
Syntax
element.insertAdjacentHTML(position, text);
Parameters
position
- A
DOMString
representing the position relative to theelement
; must be one of the following strings:'beforebegin'
: Before theelement
itself.'afterbegin'
: Just inside theelement
, before its first child.'beforeend'
: Just inside theelement
, after its last child.'afterend'
: After theelement
itself.
text
- The string to be parsed as HTML or XML and inserted into the tree.
Visualization of position names
<!--Note: Thebeforebegin
--><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.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>
Notes
Security considerations
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 the Element.insertAdjacentText()
method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.
Specifications
Specification | Status | Comment |
---|---|---|
DOM Parsing and Serialization The definition of 'Element.insertAdjacentHTML()' in that specification. | Working Draft |
Browser compatibility
BCD tables only load in the browser
See also
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论