files/en-us/web/api/element/insertadjacenttext/index.md
{{APIRef("DOM")}}
The insertAdjacentText() method of the {{domxref("Element")}} interface, given a relative position and a string, inserts a new text node at the given position relative to the element it is called from.
insertAdjacentText(where, data)
where
'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.data
where relative to the element the method is called from.None ({{jsxref("undefined")}}).
SyntaxError {{domxref("DOMException")}}
where is not a recognized value.<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
[!NOTE] The
beforebeginandafterendpositions work only if the node is in a tree and has an element parent.
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.
{{Specifications}}
{{Compat}}