The insertAdjacentText()
method of the 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.
The insertAdjacentText()
method of the 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.
js
insertAdjacentText(where, data)
where
A string representing the position relative to the element the method is called from; 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.data
A string from which to create a new text node to insert at the given position where
relative to the element the method is called from.
None (undefined
).
SyntaxError
DOMException
Thrown if where
is not a recognized value.
html
<!-- 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.
js
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.
Specification |
---|
DOM Standard # dom-element-insertadjacenttext |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
insertAdjacentText |
1 | 17 | 48 | ≤12.1 | 4 | 2.2 | 18 | 48 | ≤12.1 | 4 | 1.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText