此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Element.insertAdjacentText()

基线 广泛可用

自 2018年4月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

insertAdjacentText() 方法将一个给定的文本节点插入在相对于被调用的元素给定的位置。

语法

js
insertAdjacentText(where, data)

参数

position

A DOMString representing the position relative to the element; 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.
element

A DOMString representing the text to be inserted into the tree.

返回值

Void.

例外

Exception Explanation
SyntaxError The position specified is not a recognised value.

Visualization of position names

html
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

备注:只有当节点位于树中并具有元素父元素时,beforebegin 和 afterend 位置才能工作。

范例

js
beforeBtn.addEventListener("click", function () {
  para.insertAdjacentText("afterbegin", textInput.value);
});

afterBtn.addEventListener("click", function () {
  para.insertAdjacentText("beforeend", textInput.value);
});

Have a look at our insertAdjacentText.html demo on GitHub (see the source code too.) Here we have a simple paragraph. You can enter some text into the form element, then press the Insert before and Insert after buttons to insert it before or after the existing paragraph text using insertAdjacentText(). Note that the existing text node is not added to — further text nodes are created containing the new additions.

规范

规范
DOM
# dom-element-insertadjacenttext

浏览器兼容性

参见