Range.selectNodeContents() method sets the 范围 to contain the contents of a 节点 .

父级 节点 of the start and end of the 范围 will be the reference node. The startOffset is 0, and the endOffset is the number of child 节点 s or number of characters contained in the reference node.

句法

range.selectNodeContents(referenceNode);
					

参数

referenceNode
节点 whose contents will be selected within a 范围 .

范例

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

Live sample

This example lets the user select and deselect a paragraph with buttons. Document.createRange() , Range.selectNodeContents() ,和 Selection.addRange() are used to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it.

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
The definition of 'Range.selectNodeContents()' in that specification.
实时标准 无变化。
Document Object Model (DOM) Level 2 Traversal and Range Specification
The definition of 'Range.selectNodeContents()' in that specification.
过时 最初的规范。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
selectNodeContents Chrome Yes Edge 12 Firefox 4 IE 9 Opera 9 Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: