aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/document/evaluate/index.html
blob: 11f6cbd3727283d29b69aa4e436a896b561688c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
---
title: Document.evaluate()
slug: Web/API/Document/evaluate
translation_of: Web/API/Document/evaluate
---
<div>{{ ApiRef("DOM") }}</div>

<p>Возвращает экземпляр объекта типа <code><a href="/en-US/docs/XPathResult" title="XPathResult">XPathResult</a></code> исходя из данного <a href="/en-US/docs/XPath" title="XPath">XPath</a> и других входных параметров.</p>

<h2 id="Syntax" name="Syntax">Синтаксис</h2>

<pre class="syntaxbox notranslate">var xpathResult = document.evaluate(
 xpathExpression,
 contextNode,
 namespaceResolver,
 resultType,
 result
);</pre>

<ul>
 <li><code>xpathExpression</code> - строка, описывающая XPath, который должен быть исполнен.</li>
 <li><code>contextNode</code> указывает<em>контекстный узел</em> для запроса (см. [<a class="external" href="http://www.w3.org/TR/xpath" rel="freelink">http://www.w3.org/TR/xpath</a> спецификация XPath). В качестве данного аргумента может быть задан объект <em>document</em>.</li>
 <li><code>namespaceResolver</code> - функция, которой будут переданы все префиксы пространств имён. Она должна возвращать строку, описывающую URI, ассоциированный с данным префиксом. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. <code>null</code> is common for HTML documents or when no namespace prefixes are used.</li>
 <li><code>resultType</code> - число, описывающее тип возвращаемого <code>XPathResult</code> (см. ниже). Используйте <a href="#Result_types">именные свойства-константы</a> конструктора класса <code>XPathResult</code> (эквивалентно численным значениям от 0 до 9), как например <code>XPathResult.ANY_TYPE</code>.</li>
 <li><code>result</code> - экземпляр объекта типа <code>XPathResult</code>, используемого для хранения результатов поиска по данному <code>xpathExpression</code>. Может принимать значение <code>null</code></li>
</ul>

<h2 id="Example" name="Example">Пример</h2>

<pre class="brush: js notranslate">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
</pre>

<p>Note, in the above example, a more verbose XPath is preferred over common shortcuts such as <code>//h2</code>. 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 <em>every</em> node from the root and all subnodes looking for possible matches.</p>

<p>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:</p>

<pre class="brush: js notranslate">document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
</pre>

<p>Notice in the above <code>document.body</code> has been used as the context instead of <code>document</code> so the XPath starts from the body element. (In this example, the <code>"."</code> is important to indicate that the querying should start from the context node, document.body. If the "." was left out (leaving <code>//h2</code>) the query would start from the root node (<code>html</code>) which would be more wasteful.)</p>

<p>Более детально данный материал описан в статье <a href="/en-US/docs/Introduction_to_using_XPath_in_JavaScript" title="Introduction to using XPath in JavaScript">Introduction to using XPath in JavaScript</a>.</p>

<h2 id="Notes" name="Notes">Примечания</h2>

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

<h2 id="Result_types" name="Result_types">Типы возвращаемых данных</h2>

<p>(Merge with <a href="/Template:XPathResultConstants" title="Template:XPathResultConstants">Template:XPathResultConstants</a>?</p>

<p>These are supported values for the <code>resultType</code> parameter of the <code>evaluate</code> method:</p>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header">Result Type</td>
   <td class="header">Value</td>
   <td class="header">Description</td>
  </tr>
  <tr>
   <td><code>ANY_TYPE</code></td>
   <td>0</td>
   <td>Whatever type naturally results from the given expression.</td>
  </tr>
  <tr>
   <td><code>NUMBER_TYPE</code></td>
   <td>1</td>
   <td>A result set containing a single number. Useful, for example, in an XPath expression using the <code>count()</code> function.</td>
  </tr>
  <tr>
   <td><code>STRING_TYPE</code></td>
   <td>2</td>
   <td>A result set containing a single string.</td>
  </tr>
  <tr>
   <td><code>BOOLEAN_TYPE</code></td>
   <td>3</td>
   <td>A result set containing a single boolean value. Useful, for example, an an XPath expression using the <code>not()</code> function.</td>
  </tr>
  <tr>
   <td><code>UNORDERED_NODE_ITERATOR_TYPE</code></td>
   <td>4</td>
   <td>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.</td>
  </tr>
  <tr>
   <td><code>ORDERED_NODE_ITERATOR_TYPE</code></td>
   <td>5</td>
   <td>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.</td>
  </tr>
  <tr>
   <td><code>UNORDERED_NODE_SNAPSHOT_TYPE</code></td>
   <td>6</td>
   <td>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.</td>
  </tr>
  <tr>
   <td><code>ORDERED_NODE_SNAPSHOT_TYPE</code></td>
   <td>7</td>
   <td>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.</td>
  </tr>
  <tr>
   <td><code>ANY_UNORDERED_NODE_TYPE</code></td>
   <td>8</td>
   <td>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.</td>
  </tr>
  <tr>
   <td><code>FIRST_ORDERED_NODE_TYPE</code></td>
   <td>9</td>
   <td>A result set containing the first node in the document that matches the expression.</td>
  </tr>
 </tbody>
</table>

<p>Results of <code>NODE_ITERATOR</code> 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.</p>

<p>Results of <code>NODE_SNAPSHOT</code> 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.</p>

<h2 id="Specifications" name="Specifications">Спецификации</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator-evaluate", "Document.evaluate")}}</td>
   <td>{{Spec2("DOM3 XPath")}}</td>
   <td>Initial specification</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Совместимость с браузерами</h2>

<p>{{Compat("api.Document.evaluate")}}</p>

<h2 id="See_also" name="See_also">Смотрите также</h2>

<ul>
 <li><a href="/en-US/docs/DOM/document.createExpression" title="DOM/document.createExpression">DOM:document.createExpression</a></li>
 <li><a href="/en-US/docs/Code_snippets/XPath" title="Code_snippets/XPath">XPath Code Snippets</a></li>
 <li><a href="http://codepen.io/johan/full/ckFgn">Check for browser support</a></li>
</ul>