Range.selectNodeContents()

Range.selectNodeContents() 方法用于设置 Range,使其包含一个 Node 的内容。

Range 的起始和结束节点的父节点即为引用节点。 startOffset 为 0,  endOffset 则是引用节点包含的字符数或子节点个数。

语法

range.selectNodeContents(referenceNode);

参数

referenceNode
Node 中的内容被包含在 Range 中。

示例

range = document.createRange();
referenceNode = document.getElementsByTagName("div")[0];
range.selectNodeContents(referenceNode);

实时样例

这个例子让用户使用按钮选择或取消选择一个段落。Document.createRange()、 Range.selectNodeContents() 和 Selection.addRange() 用于选择内容。Window.getSelection()Selection.removeAllRanges() 用于取消选择。

HTML

<p id="p"><b>Use the buttons below</b> to select or deselect the contents of this paragraph.</p>
<button id="select-button">Select paragraph</button>
<button id="deselect-button">Deselect paragraph</button>

JavaScript

const p = document.getElementById('p');
const selectButton = document.getElementById('select-button');
const deselectButton = document.getElementById('deselect-button');

selectButton.addEventListener('click', e => {
  // Clear any current selection
  const selection = window.getSelection();
  selection.removeAllRanges();

  // Select paragraph
  const range = document.createRange();
  range.selectNodeContents(p);
  selection.addRange(range);
});

deselectButton.addEventListener('click', e => {
  const selection = window.getSelection();
  selection.removeAllRanges();
});

结果

规范

规范 状态 注释
DOM
Range.selectNodeContents()
Living Standard 无变化
Document Object Model (DOM) Level 2 Traversal and Range Specification
Range.selectNodeContents()
Obsolete 初始规范

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
selectNodeContentsChrome 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

参见