Skip to content

Commit 0c0487b

Browse files
committed
up
1 parent d991a8e commit 0c0487b

File tree

4 files changed

+110
-87
lines changed

4 files changed

+110
-87
lines changed

2-ui/1-document/5-searching-elements-dom/1-find-elements/solution.md

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,36 @@
1-
Есть много вариантов решения, вот некоторые из них:
1+
There are many ways to do it.
22

3-
```js
4-
// 1
5-
document.getElementById('age-table').getElementsByTagName('label');
6-
7-
// 2
8-
document.getElementById('age-table').getElementsByTagName('td')[0];
9-
// в современных браузерах можно одним запросом:
10-
var result = document.querySelector('#age-table td');
11-
12-
// 3
13-
document.getElementsByTagName('form')[1];
14-
15-
// 4
16-
document.querySelector('form[name="search"]');
3+
Here are some of them:
174

18-
// 5
19-
document.querySelector('form[name="search"] input')
20-
21-
// 6
22-
document.getElementsByName("info[0]")[0];
23-
24-
// 7
25-
document.querySelector('form[name="search-person"] [name="info[0]"]');
5+
```js
6+
// 1. The table with `id="age-table"`.
7+
let table = document.getElementById('age-table')
8+
9+
// 2. All label elements inside that table
10+
table.getElementsByTagName('label')
11+
// or
12+
document.querySelectorAll('#age-table label')
13+
14+
// 3. The first td in that table (with the word "Age").
15+
table.rows[0].cells[0]
16+
// or
17+
table.getElementsByTagName('td')[0]
18+
// or
19+
table.querySelector('td')
20+
21+
// 4. The form with the name "search".
22+
// assuming there's only one element with name="search"
23+
let form = document.getElementsByName('search')[0]
24+
// or, form specifically
25+
document.querySelector('form[name="search"]')
26+
27+
// 5. The first input in that form.
28+
form.getElementsByTagName('input')
29+
// or
30+
form.querySelector('input')
31+
32+
// 6. The last input in that form.
33+
// there's no direct query for that
34+
let inputs = form.querySelectorAll('input') // search all
35+
inputs[inputs.length-1] // take last
2636
```
27-
Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,32 @@
11
<!DOCTYPE HTML>
22
<html>
3-
4-
<head>
5-
<meta charset="utf-8">
6-
</head>
7-
83
<body>
94
<form name="search">
10-
<label>Поиск по сайту:
5+
<label>Search the site:
116
<input type="text" name="search">
127
</label>
13-
<input type="submit" value="Искать!">
8+
<input type="submit" value="Search!">
149
</form>
1510

1611
<hr>
1712

1813
<form name="search-person">
19-
Поиск по посетителям:
14+
Search the visitors:
2015
<table id="age-table">
2116
<tr>
22-
<td>Возраст:</td>
17+
<td>Age:</td>
2318
<td id="age-list">
2419
<label>
25-
<input type="radio" name="age" value="young">до 18</label>
20+
<input type="radio" name="age" value="young">less than 18</label>
2621
<label>
2722
<input type="radio" name="age" value="mature">18-50</label>
2823
<label>
29-
<input type="radio" name="age" value="senior">более 50</label>
24+
<input type="radio" name="age" value="senior">more than 50</label>
3025
</td>
3126
</tr>
3227

3328
<tr>
34-
<td>Дополнительно:</td>
29+
<td>Additionally:</td>
3530
<td>
3631
<input type="text" name="info[0]">
3732
<input type="text" name="info[1]">
@@ -41,8 +36,7 @@
4136

4237
</table>
4338

44-
<input type="submit" value="Искать!">
39+
<input type="submit" value="Search!">
4540
</form>
4641
</body>
47-
48-
</html>
42+
</html>

2-ui/1-document/5-searching-elements-dom/1-find-elements/task.md

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,17 @@ importance: 4
22

33
---
44

5-
# Поиск элементов
5+
# Search for elements
66

7-
Ниже находится документ с таблицей и формой.
7+
Here's the document with the table and form.
88

9-
Найдите (получите в переменную) в нём:
9+
How to find?
1010

11-
1. Все элементы `label` внутри таблицы. Должно быть 3 элемента.
12-
2. Первую ячейку таблицы (со словом `"Возраст"`).
13-
3. Вторую форму в документе.
14-
4. Форму с именем `search`, без использования её позиции в документе.
15-
5. Элемент `input` в форме с именем `search`. Если их несколько, то нужен первый.
16-
6. Элемент с именем `info[0]`, без точного знания его позиции в документе.
17-
7. Элемент с именем `info[0]`, внутри формы с именем `search-person`.
18-
19-
Используйте для этого консоль браузера, открыв страницу [table.html](table.html) в отдельном окне.
11+
1. The table with `id="age-table"`.
12+
2. All `label` elements inside that table (there should be 3 of them).
13+
3. The first `td` in that table (with the word "Age").
14+
4. The `form` with the name `search`.
15+
5. The first `input` in that form.
16+
6. The last `input` in that form.
2017

18+
Open the page [table.html](table.html) in a separate window and make use of browser tools for that.

2-ui/1-document/5-searching-elements-dom/article.md

Lines changed: 58 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ For instance:
4343
</script>
4444
```
4545

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`.
4848
4949
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.
5050
```
@@ -239,85 +239,107 @@ For instance:
239239
</script>
240240
```
241241
242-
## XPath в современных браузерах
242+
## Live collections
243243
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.
245245
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:
247247
248-
Все современные браузеры, кроме IE, поддерживают XPath с синтаксисом, близким к [описанному в MDN](https://developer.mozilla.org/en/XPath).
248+
```html run
249+
<div>First div</div>
249250
250-
Найдем заголовки с текстом `XPath` в текущем документе:
251+
<script>
252+
let divs = document.getElementsByTagName('div');
253+
alert(divs.length); // 1
254+
</script>
251255
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>
255257
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>
259263
```
260264
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.
262266
263-
Так как XPath сложнее и длиннее CSS, то используют его очень редко.
267+
If we use it instead, then both scripts output `1`:
264268
265-
## Итого
266269
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+
268291
<table>
269292
<thead>
270293
<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>
275298
</tr>
276299
</thead>
277300
<tbody>
278301
<tr>
279302
<td><code>getElementById</code></td>
280303
<td><code>id</code></td>
281304
<td>-</td>
282-
<td>везде</td>
305+
<td>-</td>
283306
</tr>
284307
<tr>
285308
<td><code>getElementsByName</code></td>
286309
<td><code>name</code></td>
287310
<td>-</td>
288-
<td>везде</td>
311+
<td></td>
289312
</tr>
290313
<tr>
291314
<td><code>getElementsByTagName</code></td>
292-
<td>тег или <code>'*'</code></td>
315+
<td>tag or <code>'*'</code></td>
316+
<td>✔</td>
293317
<td>✔</td>
294-
<td>везде</td>
295318
</tr>
296319
<tr>
297320
<td><code>getElementsByClassName</code></td>
298-
<td>классу</td>
321+
<td>class</td>
322+
<td>✔</td>
299323
<td>✔</td>
300-
<td>кроме IE8-</td>
301324
</tr>
302325
<tr>
303326
<td><code>querySelector</code></td>
304-
<td>CSS-селектор</td>
327+
<td>CSS-selector</td>
305328
<td>✔</td>
306-
<td>везде</td>
329+
<td>-</td>
307330
</tr>
308331
<tr>
309332
<td><code>querySelectorAll</code></td>
310-
<td>CSS-селектор</td>
333+
<td>CSS-selector</td>
311334
<td>✔</td>
312-
<td>везде</td>
335+
<td>-</td>
313336
</tr>
314337
</tbody>
315338
</table>
316339
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.
318341
319-
Кроме того:
342+
Besides:
320343
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

Comments
 (0)