The insertAdjacentText()
method inserts a given text node at a given position relative to the element it is invoked upon.
element.insertAdjacentText(position, element);
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.DOMString
representing the text to be inserted into the tree.Void.
Exception | Explanation |
---|---|
SyntaxError | The position specified is not a recognised value. |
<!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend -->
beforebegin
and afterend
positions work only if the node is in a tree and has an element parent.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.
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 greater than symbols ) }
Specification | Status | Comment |
---|---|---|
DOM The definition of 'insertAdjacentText()' in that specification. | Living Standard |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | (Yes) | 48.0 (48.0) | ? | (Yes) | (Yes) |
Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | ? | 48.0 (48.0) | ? | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/element/insertAdjacentText