Element.insertAdjacentText()
The insertAdjacentText() method of the Element interface inserts a given text node at a given position relative to the element it is invoked upon.
Syntax
element.insertAdjacentText(position, element);
Parameters
position-
A
DOMStringrepresenting the position relative to theelement; must be one of the following strings:-
'beforebegin': Before theelementitself. -
'afterbegin': Just inside theelement, before its first child. -
'beforeend': Just inside theelement, after its last child. -
'afterend': After theelementitself.
-
element-
A
DOMStringrepresenting the text to be inserted into the tree.
Return value
Void.
Exceptions
| Exception | Explanation |
|---|---|
SyntaxError | The position specified is 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.
Example
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.
Polyfill
You can polyfill the insertAdjacentText() method in Internet Explorer 5.5 (maybe earlier) and higher with the following code:
if (!Element.prototype.insertAdjacentText)
Element.prototype.insertAdjacentText = function(type, txt){
this.insertAdjacentHTML(
type,
(txt+'') // convert to string
.replace(/&/g, '&') // embed ampersand symbols
.replace(/</g, '<') // embed less-than symbols
)
}
Specifications
| Specification |
|---|
| DOM Standard (DOM) # dom-element-insertadjacenttext |
Browser compatibility
| 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
12-17
|
48 |
5
|
≤12.1 |
4 |
2.2 |
18 |
48 |
≤12.1 |
4 |
1.0 |
See also
© 2005–2021 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