--- title: Element.insertAdjacentHTML() slug: Web/API/Element/insertAdjacentHTML translation_of: Web/API/Element/insertAdjacentHTML ---
{{APIRef("DOM")}}

insertAdjacentHTML() 把傳入的字串解析成 HTML 或 XML,並把該節點插入到 DOM 樹指定的位置。它不會重新解析被使用的元素,因此他不會破壞該元素裡面原有的元素。這避免了序列化的複雜步驟,使得它比直接操作  innerHTML 快上許多。

Syntax

element.insertAdjacentHTML(position, text);

Parameters

position
A {{domxref("DOMString")}} representing the position relative to the element; must be one of the following strings:
text
text 是即將被解析並插入到 DOM 樹裡的字串。

Visualization of position names

<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->
Note:  beforebegin 和 afterend 只在該節點位於 DOM 樹內、並且有母元素時有效。

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 Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

Specification

Specification Status Comment
{{SpecName('DOM Parsing', '#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text', 'Element.insertAdjacentHTML()')}} {{ Spec2('DOM Parsing') }}  

Browser compatibility

{{Compat("api.Element.insertAdjacentHTML")}}

See also