Element: insertAdjacentText() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.
Thuộc tính insertAdjacentText() của giao diện Element, given a relative position and a string, inserts a new text node at the given position relative to the element it is called from.
Cú pháp
insertAdjacentText(where, data)
Tham số
where-
Một chuỗi representing the position relative to the element the method is called from; must be một trong các giá trị sau strings:
'beforebegin': Before theelementitself.'afterbegin': Just inside theelement, before its first child.'beforeend': Just inside theelement, after its last child.'afterend': After theelementitself.
data-
Một chuỗi from which to create a new text node to insert at the given position
whererelative to the element the method is called from.
Giá trị trả về
None (undefined).
Ngoại lệ
SyntaxErrorDOMException-
Thrown if
whereis not a recognized value.
Visualization of position names
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
Note:
The beforebegin and
afterend positions work only if the node is in a tree and has an element
parent.
Ví dụ
beforeBtn.addEventListener("click", () => {
para.insertAdjacentText("afterbegin", textInput.value);
});
afterBtn.addEventListener("click", () => {
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.
Đặc tả kỹ thuật
| Thông số kỹ thuật |
|---|
| DOM> # dom-element-insertadjacenttext> |