--- title: Element.insertAdjacentText() slug: Web/API/Element/insertAdjacentText tags: - Element.insertAdjacentText() translation_of: Web/API/Element/insertAdjacentText ---
{{APIRef("DOM")}}
insertAdjacentText()
方法将一个给定的文本节点插入在相对于被调用的元素给定的位置。
element.insertAdjacentText(position, element);
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.Void.
Exception | Explanation |
---|---|
SyntaxError |
The position specified is not a recognised value. |
<!--beforebegin
--><p>
<!--afterbegin
--> foo <!--beforeend
--></p>
<!--afterend
-->
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.
Specification | Status | Comment |
---|---|---|
{{SpecName('DOM WHATWG', '#dom-element-insertadjacenttext', 'insertAdjacentText()')}} | {{ Spec2('DOM WHATWG') }} |
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatGeckoDesktop("48.0") }} | {{ CompatUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | {{ CompatUnknown() }} | {{ CompatGeckoMobile("48.0") }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} | {{ CompatUnknown() }} |