Range.surroundContents

Range.surroundContents() 方法将 Range 对象的内容移动到一个新的节点,并将新节点放到这个范围的起始处。

这个方法与 newNode.appendChild(range.extractContents()); range.insertNode(newNode) 等价。应用以后, newNode 包含在 range 的边界点中。

然而,如果 Range 断开了一个非 Text 节点,只包含了节点的其中一个边界点,就会抛出异常。也就是说,不像上述的等价方法,如果节点仅有一部分被选中,则不会被克隆,整个操作会失败。

语法

range.surroundContents(newParent);

参数

newParent
一个包含内容的 Node

示例

HTML

<span class="header-text">Put this in a headline</span>

JavaScript

const range = document.createRange();
const newParent = document.createElement('h1');

range.selectNode(document.querySelector('.header-text'));
range.surroundContents(newParent);

结果

规范

规范 状态 注释
DOM
Range.surroundContents()
Living Standard No change.
Document Object Model (DOM) Level 2 Traversal and Range Specification
Range.surroundContents()
Obsolete Initial specification.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
surroundContentsChrome Full support YesEdge Full support 12Firefox Full support 4IE Full support 9Opera Full support 9Safari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes

Legend

Full support  
Full support

参见