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);
range = document.createRange();
referenceNode = document.getElementsByTagName("div")[0];
range.selectNodeContents(referenceNode);
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.
<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>
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();
});
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
范围
cloneContents()
cloneRange()
collapse()
compareBoundaryPoints()
compareNode()
comparePoint()
createContextualFragment()
deleteContents()
detach()
extractContents()
getBoundingClientRect()
getClientRects()
insertNode()
intersectsNode()
isPointInRange()
selectNode()
selectNodeContents()
setEnd()
setEndAfter()
setEndBefore()
setStart()
setStartAfter()
setStartBefore()
surroundContents()
toString()
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument