You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 2-ui/1-document/5-searching-elements-dom/article.md
+58-36Lines changed: 58 additions & 36 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -43,8 +43,8 @@ For instance:
43
43
</script>
44
44
```
45
45
46
-
```smart header="There must be only one"
47
-
By the specification the value of `id` must be unique. There may be only one element in the document with the given `id`.
46
+
```smart header="There can be only one"
47
+
By the specification the value of `id` must be unique. There can be only one element in the document with the given `id`.
48
48
49
49
If there are multiple elements with the same `id`, then the behavior is unpredictable. The browser may return any of them at random. So please stick to the rule and keep `id` unique.
50
50
```
@@ -239,85 +239,107 @@ For instance:
239
239
</script>
240
240
```
241
241
242
-
## XPath в современных браузерах
242
+
## Live collections
243
243
244
-
Для полноты картины рассмотрим ещё один способ поиска, который обычно используется в XML. Это <a href="http://www.w3.org/TR/xpath/">язык запросов XPath</a>.
244
+
All methods `getElementsBy*` return a *live* collection. They always reflect the current state of the document.
245
245
246
-
Он очень мощный, во многом мощнее CSS, но сложнее. Например, запрос для поиска элементов `H2`, содержащих текст `"XPath"`, будет выглядеть так: `//h2[contains(., "XPath")]`.
246
+
For instance, here in the first script the length is `1`, because the browser only processed the first div. Then later it's 2:
247
247
248
-
Все современные браузеры, кроме IE, поддерживают XPath с синтаксисом, близким к [описанному в MDN](https://developer.mozilla.org/en/XPath).
248
+
```html run
249
+
<div>First div</div>
249
250
250
-
Найдем заголовки с текстом `XPath` в текущем документе:
251
+
<script>
252
+
let divs = document.getElementsByTagName('div');
253
+
alert(divs.length); // 1
254
+
</script>
251
255
252
-
```js run no-beautify
253
-
var result = document.evaluate("//h2[contains(., 'XPath')]", document.documentElement, null,
254
-
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
256
+
<div>Second div</div>
255
257
256
-
for (var i = 0; i < result.snapshotLength; i++) {
257
-
alert( result.snapshotItem(i).outerHTML );
258
-
}
258
+
<script>
259
+
*!*
260
+
alert(divs.length); // 2
261
+
*/!*
262
+
</script>
259
263
```
260
264
261
-
IE тоже поддерживает XPath, но эта поддержка не соответствует стандарту и работает только для XML-документов, например, полученных с помощью `XMLHTTPRequest` (AJAX). Для обычных же HTML-документов XPath в IE не поддерживается.
265
+
In contrast, `querySelectorAll` returns a *static* collection. It's like a fixed array of elements.
262
266
263
-
Так как XPath сложнее и длиннее CSS, то используют его очень редко.
267
+
If we use it instead, then both scripts output `1`:
264
268
265
-
## Итого
266
269
267
-
Есть 6 основных методов поиска элементов DOM:
270
+
```html run
271
+
<div>First div</div>
272
+
273
+
<script>
274
+
let divs = document.querySelectorAll('div');
275
+
alert(divs.length); // 1
276
+
</script>
277
+
278
+
<div>Second div</div>
279
+
280
+
<script>
281
+
*!*
282
+
alert(divs.length); // 1
283
+
*/!*
284
+
</script>
285
+
```
286
+
287
+
## Summary
288
+
289
+
There are 6 main methods to search for nodes in DOM:
290
+
268
291
<table>
269
292
<thead>
270
293
<tr>
271
-
<td>Метод</td>
272
-
<td>Ищет по...</td>
273
-
<td>Ищет внутри элемента?</td>
274
-
<td>Поддержка</td>
294
+
<td>Method</td>
295
+
<td>Finds by...</td>
296
+
<td>Can call on element?</td>
297
+
<td>Live?</td>
275
298
</tr>
276
299
</thead>
277
300
<tbody>
278
301
<tr>
279
302
<td><code>getElementById</code></td>
280
303
<td><code>id</code></td>
281
304
<td>-</td>
282
-
<td>везде</td>
305
+
<td>-</td>
283
306
</tr>
284
307
<tr>
285
308
<td><code>getElementsByName</code></td>
286
309
<td><code>name</code></td>
287
310
<td>-</td>
288
-
<td>везде</td>
311
+
<td>✔</td>
289
312
</tr>
290
313
<tr>
291
314
<td><code>getElementsByTagName</code></td>
292
-
<td>тег или <code>'*'</code></td>
315
+
<td>tag or <code>'*'</code></td>
316
+
<td>✔</td>
293
317
<td>✔</td>
294
-
<td>везде</td>
295
318
</tr>
296
319
<tr>
297
320
<td><code>getElementsByClassName</code></td>
298
-
<td>классу</td>
321
+
<td>class</td>
322
+
<td>✔</td>
299
323
<td>✔</td>
300
-
<td>кроме IE8-</td>
301
324
</tr>
302
325
<tr>
303
326
<td><code>querySelector</code></td>
304
-
<td>CSS-селектор</td>
327
+
<td>CSS-selector</td>
305
328
<td>✔</td>
306
-
<td>везде</td>
329
+
<td>-</td>
307
330
</tr>
308
331
<tr>
309
332
<td><code>querySelectorAll</code></td>
310
-
<td>CSS-селектор</td>
333
+
<td>CSS-selector</td>
311
334
<td>✔</td>
312
-
<td>везде</td>
335
+
<td>-</td>
313
336
</tr>
314
337
</tbody>
315
338
</table>
316
339
317
-
Практика показывает, что в 95% ситуаций достаточно `querySelector/querySelectorAll`. Хотя более специализированные методы `getElement*` работают чуть быстрее, но разница в миллисекунду-другую редко играет роль.
340
+
Please note that methods `getElementById` and `getElementsByName` can only be called in the context of the document: `document.getElementById(...)`. Other methods can be called on elements, like `elem.querySelectorAll(...)` -- and will search in their subtrees.
318
341
319
-
Кроме того:
342
+
Besides:
320
343
321
-
- Есть метод `elem.matches(css)`, который проверяет, удовлетворяет ли элемент CSS-селектору. Он поддерживается большинством браузеров в префиксной форме (`ms`, `moz`, `webkit`).
322
-
- Метод `elem.closest(css)` ищет ближайший элемент выше по иерархии DOM, подходящий под CSS-селектор css. Сам элемент тоже включается в поиск.
323
-
- Язык запросов XPath поддерживается большинством браузеров, кроме IE, даже 9-й версии, но `querySelector` удобнее. Поэтому XPath используется редко.
344
+
- There is `elem.matches(css)` to check if `elem` matches the given CSS selector.
345
+
- There is `elem.closest(css)` to look for a nearest ancestor that matches the given CSS-selector. The `elem` itself is also checked.
0 commit comments