Element.insertAdjacentText() - Web APIs 编辑
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
DOMString
representing the position relative to theelement
; must be one of the following strings:'beforebegin'
: Before theelement
itself.'afterbegin'
: Just inside theelement
, before its first child.'beforeend'
: Just inside theelement
, after its last child.'afterend'
: After theelement
itself.
element
- A
DOMString
representing the text to be inserted into the tree.
Return value
Void.
Exceptions
Exception | Explanation |
---|---|
SyntaxError | The position specified is not a recognised value. |
Visualization of position names
<!--Note: Thebeforebegin
--><p>
<!--afterbegin
--> foo <!--beforeend
--></p>
<!--afterend
-->
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 | Status | Comment |
---|---|---|
DOM The definition of 'insertAdjacentText()' in that specification. | Living Standard |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论