Skip to content

Commit f1c2506

Browse files
committed
2-ui/1-document/03-dom-navigation: part 2
1 parent e407870 commit f1c2506

2 files changed

Lines changed: 72 additions & 72 deletions

File tree

‎2-ui/1-document/03-dom-navigation/article.md‎

Lines changed: 71 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -127,129 +127,129 @@ elem.childNodes[elem.childNodes.length - 1] === elem.lastChild
127127
128128
Існує також спеціальна функція `elem.hasChildNodes()`, що перевіряє, чи є взагалі дочірні вузли.
129129
130-
### DOM collections
130+
### DOM колекції
131131
132-
As we can see, `childNodes` looks like an array. But actually it's not an array, but rather a *collection* -- a special array-like iterable object.
132+
Як бачимо, `childNodes` виглядає як масив. Але насправді це не масив, а скоріше *колекція* -- спеціальний ітеративний об’єкт, подібний до масиву.
133133
134-
There are two important consequences:
134+
Є два важливих наслідки:
135135
136-
1. We can use `for..of` to iterate over it:
136+
1. Ми можемо використовувати `for..of`, щоб перебирати його:
137137
```js
138138
for (let node of document.body.childNodes) {
139-
alert(node); // shows all nodes from the collection
139+
alert(node); // показує всі вузли з колекції
140140
}
141141
```
142-
That's because it's iterable (provides the `Symbol.iterator` property, as required).
142+
Це тому, що він ітерований (підчас перебору може надавати властивість `Symbol.iterator`).
143143
144-
2. Array methods won't work, because it's not an array:
144+
2. Методи масиву не працюватимуть, тому що це не масив:
145145
```js run
146-
alert(document.body.childNodes.filter); // undefined (there's no filter method!)
146+
alert(document.body.childNodes.filter); // undefined (методу filter немає!)
147147
```
148148
149-
The first thing is nice. The second is tolerable, because we can use `Array.from` to create a "real" array from the collection, if we want array methods:
149+
Перший наслідок приємний, з другим можна змиритися, оскільки ми можемо використовувати `Array.from` для створення "справжнього" масиву з колекції, якщо нам потрібні методи масиву:
150150
151151
```js run
152152
alert( Array.from(document.body.childNodes).filter ); // function
153153
```
154154
155-
```warn header="DOM collections are read-only"
156-
DOM collections, and even more -- *all* navigation properties listed in this chapter are read-only.
155+
```warn header="Колекції DOM доступні лише для считування"
156+
Колекції DOM і навіть більше -- *всі* властивості навігації, перелічені в цьому розділі, доступні лише для считування.
157157
158-
We can't replace a child by something else by assigning `childNodes[i] = ...`.
158+
Ми не можемо замінити дочірній елемент на щось інше, призначивши `childNodes[i] = ...`.
159159
160-
Changing DOM needs other methods. We will see them in the next chapter.
160+
Для зміни DOM потрібні інші методи. Ми розберемо їх у наступному розділі.
161161
```
162162
163-
```warn header="DOM collections are live"
164-
Almost all DOM collections with minor exceptions are *live*. In other words, they reflect the current state of DOM.
163+
```warn header="DOM колецкції живі"
164+
Майже всі колекції DOM, за незначними винятками, є *живими*. Іншими словами, вони завжди відображають поточний стан DOM.
165165
166-
If we keep a reference to `elem.childNodes`, and add/remove nodes into DOM, then they appear in the collection automatically.
166+
Якщо ми зберегли посилання на `elem.childNodes` і після цього додамо/видалемо вузли в DOM, вони автоматично з’являться в колекції.
167167
```
168168
169-
````warn header="Don't use `for..in` to loop over collections"
170-
Collections are iterable using `for..of`. Sometimes people try to use `for..in` for that.
169+
````warn header="Не використовуйте `for..in` для перебору колекцій"
170+
Колекції можна перебирати за допомогою `for..of`. Але іноді люди намагаються використовувати для цього `for..in`.
171171
172-
Please, don't. The `for..in` loop iterates over all enumerable properties. And collections have some "extra" rarely used properties that we usually do not want to get:
172+
Будь ласка, не треба. Цикл `for..in` перебирає всі властивості без виключення. А колекції мають деякі "додаткові" рідко використовувані властивості, які ми зазвичай не хочемо отримувати:
173173
174174
```html run
175175
<body>
176176
<script>
177-
// shows 0, 1, length, item, values and more.
177+
// показує 0, 1, length, item, values і більше.
178178
for (let prop in document.body.childNodes) alert(prop);
179179
</script>
180180
</body>
181181
````
182182

183-
## Siblings and the parent
183+
## Сусідні і батьківський елементи
184184

185-
*Siblings* are nodes that are children of the same parent.
185+
*Сусіди*, або сусідні вузли -- це вузли, які мають однаковий батьківський елемент.
186186

187-
For instance, here `<head>` and `<body>` are siblings:
187+
Наприклад, тут `<head>` і `<body>` є сусідами:
188188

189189
```html
190190
<html>
191191
<head>...</head><body>...</body>
192192
</html>
193193
```
194194

195-
- `<body>` is said to be the "next" or "right" sibling of `<head>`,
196-
- `<head>` is said to be the "previous" or "left" sibling of `<body>`.
195+
- `<body>` вважається "наступним" або сусідом "праворуч" для `<head>`,
196+
- `<head>` вважається "попереднім" або сусідом "ліворуч" для `<body>`.
197197

198-
The next sibling is in `nextSibling` property, and the previous one - in `previousSibling`.
198+
Наступний сусід знаходиться у властивості `nextSibling`, а попередній -- у `previousSibling`.
199199

200-
The parent is available as `parentNode`.
200+
Батьківський вузол доступний як `parentNode`.
201201

202-
For example:
202+
Наприклад:
203203

204204
```js run
205-
// parent of <body> is <html>
205+
// батьком <body> є <html>
206206
alert( document.body.parentNode === document.documentElement ); // true
207207

208-
// after <head> goes <body>
208+
// після <head> іде <body>
209209
alert( document.head.nextSibling ); // HTMLBodyElement
210210

211-
// before <body> goes <head>
211+
// після <body> іде <head>
212212
alert( document.body.previousSibling ); // HTMLHeadElement
213213
```
214214

215-
## Element-only navigation
215+
## Навігація лише за елементами
216216

217-
Navigation properties listed above refer to *all* nodes. For instance, in `childNodes` we can see both text nodes, element nodes, and even comment nodes if they exist.
217+
Властивості навігації, перераховані вище, відносяться до *всіх* вузлів. Наприклад, у `childNodes` ми можемо побачити як текстові вузли, так і вузли елементів і навіть вузли коментарів, якщо вони існують.
218218

219-
But for many tasks we don't want text or comment nodes. We want to manipulate element nodes that represent tags and form the structure of the page.
219+
Але для багатьох задач нам не потрібні текстові вузли чи вузли коментарів. Ми хочемо маніпулювати вузлами елементів, які представляють теги та формують структуру сторінки.
220220

221-
So let's see more navigation links that only take *element nodes* into account:
221+
Тож давайте подивимося властивости зі спеціальними посиланнями, які враховують лише *вузли елементи*:
222222

223223
![](dom-links-elements.svg)
224224

225-
The links are similar to those given above, just with `Element` word inside:
225+
Посилання подібні до наведених вище, лише із словом `Element` всередині:
226226

227-
- `children` -- only those children that are element nodes.
228-
- `firstElementChild`, `lastElementChild` -- first and last element children.
229-
- `previousElementSibling`, `nextElementSibling` -- neighbor elements.
230-
- `parentElement` -- parent element.
227+
- `children` -- тільки ті дочірні елементи, які є вузлами елементами.
228+
- `firstElementChild`, `lastElementChild` -- перший і останній дочірні елементи.
229+
- `previousElementSibling`, `nextElementSibling` -- сусідні елементи.
230+
- `parentElement` -- батьківський елемент.
231231

232-
````smart header="Why `parentElement`? Can the parent be *not* an element?"
233-
The `parentElement` property returns the "element" parent, while `parentNode` returns "any node" parent. These properties are usually the same: they both get the parent.
232+
````smart header="Чому `parentElement`? Чи може батько бути *не* елементом?"
233+
Властивість `parentElement` повертає батьківський елемент "element", тоді як `parentNode` повертає батьківський "будь-який вузол". Ці властивості зазвичай однакові: обидва вони отримують батьківський елемент.
234234

235-
With the one exception of `document.documentElement`:
235+
За одним винятком `document.documentElement`:
236236

237237
```js run
238238
alert( document.documentElement.parentNode ); // document
239239
alert( document.documentElement.parentElement ); // null
240240
```
241241

242-
The reason is that the root node `document.documentElement` (`<html>`) has `document` as its parent. But `document` is not an element node, so `parentNode` returns it and `parentElement` does not.
242+
Причина в тому, що кореневий вузол `document.documentElement` (`<html>`) має `document` як батьківський. Але він має тип `document` -- це не елемент, тому `parentNode` повертає його, а `parentElement` ні.
243243

244-
This detail may be useful when we want to travel up from an arbitrary element `elem` to `<html>`, but not to the `document`:
244+
Ця деталь може бути корисною, коли ми хочемо перейти від довільного елемента `elem` до `<html>`, але не до `document`:
245245
```js
246-
while(elem = elem.parentElement) { // go up till <html>
246+
while(elem = elem.parentElement) { // ідемо вверх поки не дійдемо до <html>
247247
alert( elem );
248248
}
249249
```
250250
````
251251
252-
Let's modify one of the examples above: replace `childNodes` with `children`. Now it shows only elements:
252+
Давайте змінимо один із прикладів вище: замінимо `childNodes` на `children`. Тепер він показує лише елементи:
253253
254254
```html run
255255
<html>
@@ -274,31 +274,31 @@ Let's modify one of the examples above: replace `childNodes` with `children`. No
274274
</html>
275275
```
276276
277-
## More links: tables [#dom-navigation-tables]
277+
## Ще корисних властивостей: таблиці [#dom-navigation-tables]
278278
279-
Till now we described the basic navigation properties.
279+
До цих пір ми описали основні властивості для навігації.
280280
281-
Certain types of DOM elements may provide additional properties, specific to their type, for convenience.
281+
Деякі типи елементів DOM можуть надавати додаткові властивості, специфічні для їх типу, для зручності.
282282
283-
Tables are a great example of that, and represent a particularly important case:
283+
Таблиці є чудовим прикладом цього і представляють особливо важливий випадок:
284284
285-
**The `<table>`** element supports (in addition to the given above) these properties:
286-
- `table.rows` -- the collection of `<tr>` elements of the table.
287-
- `table.caption/tHead/tFoot` -- references to elements `<caption>`, `<thead>`, `<tfoot>`.
288-
- `table.tBodies` -- the collection of `<tbody>` elements (can be many according to the standard, but there will always be at least one -- even if it is not in the source HTML, the browser will put it in the DOM).
285+
**Елемент`<table>`** підтримує (на додаток до наведених вище) такі властивості:
286+
- `table.rows` -- набір елементів `<tr>` таблиці.
287+
- `table.caption/tHead/tFoot` -- посилання на елементи `<caption>`, `<thead>`, `<tfoot>`.
288+
- `table.tBodies` -- колекція елементів `<tbody>` (за стандартом може бути багато, але завжди буде принаймні один -- навіть якщо його немає у вихідному HTML, браузер помістить його в DOM).
289289
290-
**`<thead>`, `<tfoot>`, `<tbody>`** elements provide the `rows` property:
291-
- `tbody.rows` -- the collection of `<tr>` inside.
290+
**Елементи `<thead>`, `<tfoot>`, `<tbody>`** забезпечують властивість `rows`:
291+
- `tbody.rows` -- колекція `<tr>` всередині.
292292
293293
**`<tr>`:**
294-
- `tr.cells` -- the collection of `<td>` and `<th>` cells inside the given `<tr>`.
295-
- `tr.sectionRowIndex` -- the position (index) of the given `<tr>` inside the enclosing `<thead>/<tbody>/<tfoot>`.
296-
- `tr.rowIndex` -- the number of the `<tr>` in the table as a whole (including all table rows).
294+
- `tr.cells` -- колекція клітинок `<td>` і `<th>` всередині заданого рядка `<tr>`.
295+
- `tr.sectionRowIndex` -- позиція (індекс) заданого `<tr>` всередині батьківського `<thead>/<tbody>/<tfoot>`.
296+
- `tr.rowIndex` -- номер (індекс) рядка `<tr>` у таблиці в цілому (враховуючи всі рядки таблиці без виключення).
297297
298-
**`<td>` and `<th>`:**
299-
- `td.cellIndex` -- the number of the cell inside the enclosing `<tr>`.
298+
**`<td>` і `<th>`:**
299+
- `td.cellIndex` -- номер клітинки у рядку `<tr>`.
300300
301-
An example of usage:
301+
Приклад використання:
302302
303303
```html run height=100
304304
<table id="table">
@@ -317,17 +317,17 @@ An example of usage:
317317
</script>
318318
```
319319
320-
The specification: [tabular data](https://html.spec.whatwg.org/multipage/tables.html).
320+
Специфікація: [табличні дані](https://html.spec.whatwg.org/multipage/tables.html).
321321
322-
There are also additional navigation properties for HTML forms. We'll look at them later when we start working with forms.
322+
Існують також додаткові властивості навігації для HTML-форм. Ми розглянемо їх пізніше, коли почнемо працювати з формами.
323323
324-
## Summary
324+
## Підсумки
325325
326-
Given a DOM node, we can go to its immediate neighbors using navigation properties.
326+
Для вузла DOM, ми можемо перейти до його безпосередніх сусідів за допомогою властивостей навігації.
327327
328-
There are two main sets of them:
328+
Існує два основних набори:
329329
330-
- For all nodes: `parentNode`, `childNodes`, `firstChild`, `lastChild`, `previousSibling`, `nextSibling`.
331-
- For element nodes only: `parentElement`, `children`, `firstElementChild`, `lastElementChild`, `previousElementSibling`, `nextElementSibling`.
330+
- Для всіх вузлів: `parentNode`, `childNodes`, `firstChild`, `lastChild`, `previousSibling`, `nextSibling`.
331+
- Лише для вузлів елементів: `parentElement`, `children`, `firstElementChild`, `lastElementChild`, `previousElementSibling`, `nextElementSibling`.
332332
333-
Some types of DOM elements, e.g. tables, provide additional properties and collections to access their content.
333+
Деякі типи елементів DOM, напр. таблиці, надають додаткові властивості та колекції для доступу до їх вмісту.

0 commit comments

Comments
 (0)