Movatterモバイル変換


[0]ホーム

URL:


  1. Веб-технологии для разработчиков
  2. Интерфейсы веб API
  3. Document
  4. Document.evaluate()

This page was translated from English by the community.Learn more and join the MDN Web Docs community.

View in EnglishAlways switch to English

Document.evaluate()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨июль 2015 г.⁩.

Возвращает экземпляр объекта типаXPathResult исходя из данногоXPath и других входных параметров.

Синтаксис

var xpathResult = document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result);
  • xpathExpression - строка, описывающая XPath, который должен быть исполнен.
  • contextNode указываетконтекстный узел для запроса (см. [http://www.w3.org/TR/xpath спецификация XPath). В качестве данного аргумента может быть задан объектdocument.
  • namespaceResolver - функция, которой будут переданы все префиксы пространств имён. Она должна возвращать строку, описывающую URI, ассоциированный с данным префиксом. 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 - число, описывающее тип возвращаемогоXPathResult (см. ниже). Используйтеименные свойства-константы конструктора классаXPathResult (эквивалентно численным значениям от 0 до 9), как напримерXPathResult.ANY_TYPE.
  • result - экземпляр объекта типаXPathResult, используемого для хранения результатов поиска по данномуxpathExpression. Может принимать значениеnull

Пример

js
var headings = document.evaluate(  "/html/body//h2",  document,  null,  XPathResult.ANY_TYPE,  null,);/* Найти в документе все элементы h2 * В качестве результата будет получен узловой итератор. */var thisHeading = headings.iterateNext();var alertText = "В данном документе заголовками 2-го уровня являются:\n";while (thisHeading) {  alertText += thisHeading.textContent + "\n";  thisHeading = headings.iterateNext();}alert(alertText); // Показывает alert со всеми найденными элементами h2

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 visitsevery 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:

js
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);

Notice in the abovedocument.body has been used as the context instead ofdocument 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.

Примечания

  • Выражения XPath могут быть интерпретированы в HTML- и XML-документах.
  • While using document.evaluate() works in FF2, in FF3 one must use someXMLDoc.evaluate() if evaluating against something other than the current document.

Типы возвращаемых данных

These are supported values for theresultType parameter of theevaluate method:

Result TypeValueDescription
ANY_TYPE0Whatever type naturally results from the given expression.
NUMBER_TYPE1A result set containing a single number. Useful, for example, in an XPath expression using thecount() function.
STRING_TYPE2A result set containing a single string.
BOOLEAN_TYPE3A result set containing a single boolean value. Useful, for example, an an XPath expression using thenot() function.
UNORDERED_NODE_ITERATOR_TYPE4A 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_TYPE5A 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_TYPE6A 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_TYPE7A 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_TYPE8A 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_TYPE9A result set containing the first node in the document that matches the expression.

Results ofNODE_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 ofNODE_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.

Спецификации

Specification
DOM
# dom-xpathevaluatorbase-evaluate

Совместимость с браузерами

Смотрите также

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp