返回
XPathResult
based on an
XPath
expression and other given parameters.
var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );
xpathExpression
is a string representing the XPath to be evaluated.
contextNode
specifies the
context node
for the query (see the
XPath specification
). It's common to pass
document
as the context node.
namespaceResolver
is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document.
null
is common for HTML documents or when no namespace prefixes are used.
resultType
is an integer that corresponds to the type of result
XPathResult
to return. Use
named constant properties
,譬如
XPathResult.ANY_TYPE
, of the XPathResult constructor, which correspond to integers from 0 to 9.
result
is an existing
XPathResult
to use for the results.
null
is the most common and will create a new
XPathResult
var headings = document.evaluate("/html/body//h2", document, null, XPathResult.ANY_TYPE, null);
/* Search the document for all h2 elements.
* The result will likely be an unordered node iterator. */
var thisHeading = headings.iterateNext();
var alertText = "Level 2 headings in this document are:\n";
while (thisHeading) {
alertText += thisHeading.textContent + "\n";
thisHeading = headings.iterateNext();
}
alert(alertText); // Alerts the text of all h2 elements
Note, in the above example, a more verbose XPath is preferred over common shortcuts such as
//h2
. Generally, more specific XPath selectors as in the above example usually gives a significant performance improvement, especially on very large documents. This is because the evaluation of the query spends does not waste time visiting unnecessary nodes. Using // is generally slow as it visits
every
node from the root and all subnodes looking for possible matches.
Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the body tag, you can use this:
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
Notice in the above
document.body
has been used as the context instead of
document
so the XPath starts from the body element. (In this example, the
"."
is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving
//h2
) the query would start from the root node (
html
) which would be more wasteful.)
见 Introduction to using XPath in JavaScript 了解更多信息。
(Merge with Template:XPathResultConstants ?
These are supported values for the
resultType
参数为
evaluate
方法:
| 结果类型 | 值 | 描述 |
ANY_TYPE
|
0 | Whatever type naturally results from the given expression. |
NUMBER_TYPE
|
1 |
A result set containing a single number. Useful, for example, in an XPath expression using the
count()
函数。
|
STRING_TYPE
|
2 | A result set containing a single string. |
BOOLEAN_TYPE
|
3 |
A result set containing a single boolean value. Useful, for example, an an XPath expression using the
not()
函数。
|
UNORDERED_NODE_ITERATOR_TYPE
|
4 | A result set containing all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document. |
ORDERED_NODE_ITERATOR_TYPE
|
5 | A result set containing all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document. |
UNORDERED_NODE_SNAPSHOT_TYPE
|
6 | A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are not necessarily in the same order they appear in the document. |
ORDERED_NODE_SNAPSHOT_TYPE
|
7 | A result set containing snapshots of all the nodes matching the expression. The nodes in the result set are in the same order they appear in the document. |
ANY_UNORDERED_NODE_TYPE
|
8 | A result set containing any single node that matches the expression. The node is not necessarily the first node in the document that matches the expression. |
FIRST_ORDERED_NODE_TYPE
|
9 | A result set containing the first node in the document that matches the expression. |
Results of
NODE_ITERATOR
types contain references to nodes in the document. Modifying a node will invalidate the iterator. After modifying a node, attempting to iterate through the results will result in an error.
Results of
NODE_SNAPSHOT
types are snapshots, which are essentially lists of matched nodes. You can make changes to the document by altering snapshot nodes. Modifying the document doesn't invalidate the snapshot; however, if the document is changed, the snapshot may not correspond to the current state of the document, since nodes may have moved, been changed, added, or removed.
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM (文档对象模型) 3 级 XPath 规范
The definition of 'Document.evaluate' in that specification. |
推荐 | Initial specification |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
evaluate
|
Chrome 1 | Edge 12 | Firefox 1.5 | IE No | Opera 9 | Safari 5 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 4.2 | Samsung Internet Android 1.0 |
完整支持
不支持
Document
alinkColor
all
anchors
applets
bgColor
body
characterSet
childElementCount
children
compatMode
contentType
currentScript
defaultView
designMode
dir
doctype
documentElement
documentURI
documentURIObject
domain
domConfig
嵌入
fgColor
firstElementChild
forms
fullscreen
fullscreenEnabled
head
height
hidden
图像
实现
lastElementChild
lastModified
lastStyleSheetSet
linkColor
链接
location
mozSyntheticDocument
onabort
onafterscriptexecute
onanimationcancel
onanimationend
onanimationiteration
onauxclick
onbeforescriptexecute
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondurationchange
onended
onerror
onfocus
onformdata
onfullscreenchange
onfullscreenerror
ongotpointercapture
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onoffline
ononline
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onvisibilitychange
onwheel
origin
plugins
popupNode
preferredStyleSheetSet
readyState
referrer
rootElement
脚本
scrollingElement
selectedStyleSheetSet
styleSheetSets
timeline
title
tooltipNode
URL
visibilityState
vlinkColor
width
xmlEncoding
xmlVersion
adoptNode()
append()
caretRangeFromPoint()
clear()
close()
createAttribute()
createCDATASection()
createComment()
createDocumentFragment()
createElement()
createElementNS()
createEntityReference()
createEvent()
createExpression()
createExpression()
createNodeIterator()
createNSResolver()
createNSResolver()
createProcessingInstruction()
createRange()
createTextNode()
createTouch()
createTouchList()
createTreeWalker()
enableStyleSheetsForSet()
evaluate()
evaluate()
execCommand()
exitFullscreen()
exitPointerLock()
getAnimations()
getBoxObjectFor()
getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
hasFocus()
hasStorageAccess()
importNode()
mozSetImageElement()
open()
prepend()
queryCommandEnabled()
queryCommandSupported()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
registerElement()
releaseCapture()
replaceChildren()
requestStorageAccess()
write()
writeln()
animationcancel
animationend
animationiteration
animationstart
copy
cut
DOMContentLoaded
drag
dragend
dragenter
dragexit
dragleave
dragover
dragstart
drop
fullscreenchange
fullscreenerror
gotpointercapture
keydown
keypress
keyup
lostpointercapture
paste
pointercancel
pointerdown
pointerenter
pointerleave
pointerlockchange
pointerlockerror
pointermove
pointerout
pointerover
pointerup
readystatechange
scroll
selectionchange
selectstart
touchcancel
touchend
touchmove
touchstart
transitioncancel
transitionend
transitionrun
transitionstart
visibilitychange
wheel
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
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument