Skip to content

Commit

Permalink
Basic DOM Node Properties (javascript-tutorial#260)
Browse files Browse the repository at this point in the history
  • Loading branch information
MykolaSopiha authored and malechaneit committed Feb 2, 2022
1 parent a0446e4 commit 0925650
Show file tree
Hide file tree
Showing 11 changed files with 263 additions and 263 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
There's a catch here.
Тут є пастка.

At the time of `<script>` execution the last DOM node is exactly `<script>`, because the browser did not process the rest of the page yet.
У момент виконання `<script>` останній вузол DOM є саме `<script>`, тому що браузер ще не обробив решту сторінки.

So the result is `1` (element node).
Отже, результат -- `1` (вузол-елемент).

```html run height=60
<html>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# What's in the nodeType?
# Що в nodeType?

What does the script show?
Що показує скрипт?

```html
<html>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
Let's make a loop over `<li>`:
Давайте зробимо цикл по `<li>`:

```js
for (let li of document.querySelectorAll('li')) {
...
}
```

In the loop we need to get the text inside every `li`.
У циклі нам потрібно отримати текст всередині кожного `li`.

We can read the text from the first child node of `li`, that is the text node:
Ми можемо прочитати текст з першого дочірнього вузла `li`, це текстовий вузол:

```js
for (let li of document.querySelectorAll('li')) {
let title = li.firstChild.data;

// title is the text in <li> before any other nodes
// title -- це текст в <li> перед будь-якими іншими вузлами
}
```

Then we can get the number of descendants as `li.getElementsByTagName('li').length`.
Тоді ми можемо отримати кількість нащадків як `li.getElementsByTagName('li').length`.
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,36 @@
<body>

<ul>
<li>Animals
<li>Тварини
<ul>
<li>Mammals
<li>Ссавці
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
<li>Корови</li>
<li>Осли</li>
<li>Собаки</li>
<li>Тигри</li>
</ul>
</li>
<li>Other
<li>Інші
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
<li>Змії</li>
<li>Птахи</li>
<li>Ящірки</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<li>Риби
<ul>
<li>Aquarium
<li>Акваріум
<ul>
<li>Guppy</li>
<li>Angelfish</li>
<li>Гупі</li>
<li>Ангельська рибка</li>
</ul>
</li>
<li>Sea
<li>Море
<ul>
<li>Sea trout</li>
<li>Морська форель</li>
</ul>
</li>
</ul>
Expand All @@ -41,12 +41,12 @@

<script>
for (let li of document.querySelectorAll('li')) {
// get the title from the text node
// отримайємо назву з текстового вузла
let title = li.firstChild.data;

title = title.trim(); // remove extra spaces from ends
title = title.trim(); // видалимо додаткові пробіли з кінця

// get the descendants count
// отримаємо кількість нащадків
let count = li.getElementsByTagName('li').length;

alert(title + ': ' + count);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,44 @@
<body>

<ul>
<li>Animals
<li>Тварини
<ul>
<li>Mammals
<li>Ссавці
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
<li>Корів</li>
<li>Осли</li>
<li>Собаки</li>
<li>Тигер</li>
</ul>
</li>
<li>Other
<li>Інші
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
<li>Змії</li>
<li>Птахи</li>
<li>Ящірки</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<li>Риби
<ul>
<li>Aquarium
<li>Акваріум
<ul>
<li>Guppy</li>
<li>Angelfish</li>
<li>Гуппі</li>
<li>Ангельський</li>
</ul>
</li>
<li>Sea
<li>Море
<ul>
<li>Sea trout</li>
<li>Морська форель</li>
</ul>
</li>
</ul>
</li>
</ul>

<script>
// ... your code...
// ... ваш код...
</script>

</body>
Expand Down
10 changes: 5 additions & 5 deletions 2-ui/1-document/05-basic-dom-node-properties/2-tree-info/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Count descendants
# Підрахувати нащадків

There's a tree structured as nested `ul/li`.
Є дерево, що структуровано як вкладені `ul/li`.

Write the code that for each `<li>` shows:
Напишіть код, який для кожного `<li>` показує:

1. What's the text inside it (without the subtree)
2. The number of nested `<li>` -- all descendants, including the deeply nested ones.
1. Текст всередині вузла (без піддерева)
2. Кількість вкладених `<li>` -- всіх нащадків, включаючи глибоко вкладені.

[demo src="solution"]
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: **`BODY`**.
Відповідь: **`BODY`**.

```html run
<script>
Expand All @@ -10,8 +10,8 @@ The answer: **`BODY`**.
</script>
```

What's going on step by step:
Що відбувається крок за кроком:

1. The content of `<body>` is replaced with the comment. The comment is `<!--BODY-->`, because `body.tagName == "BODY"`. As we remember, `tagName` is always uppercase in HTML.
2. The comment is now the only child node, so we get it in `body.firstChild`.
3. The `data` property of the comment is its contents (inside `<!--...-->`): `"BODY"`.
1. Вміст `<body>` замінюється коментарем. Коментар `<!--BODY-->`, тому що `body.tagName == "BODY"`. Як ми пам’ятаємо, `tagName` завжди пишеться великими літерами в HTML.
2. Коментар зараз є єдиним дочірнім вузлом, тому ми отримуємо його в `body.firstChild`.
3. Властивість коментаря `data` -- це його вміст (всередині `<!--...-->`): `"BODY"`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ importance: 3

---

# Tag in comment
# Тег у коментарі

What does this code show?
Що показує цей код?

```html
<script>
let body = document.body;
body.innerHTML = "<!--" + body.tagName + "-->";
alert( body.firstChild.data ); // what's here?
alert( body.firstChild.data ); // що тут?
</script>
```
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@

We can see which class it belongs by outputting it, like:
Ми можемо побачити, якому класу він належить вивівши його, наприклад:

```js run
alert(document); // [object HTMLDocument]
```

Or:
Або:

```js run
alert(document.constructor.name); // HTMLDocument
```

So, `document` is an instance of `HTMLDocument` class.
Отже, `document` -- це екземпляр класу `HTMLDocument`.

What's its place in the hierarchy?
Яке його місце в ієрархії?

Yeah, we could browse the specification, but it would be faster to figure out manually.
Так, ми могли б переглянути специфікацію, але було б швидше з’ясувати вручну.

Let's traverse the prototype chain via `__proto__`.
Давайте пройдемо по ланцюгу прототипів через `__proto__`.

As we know, methods of a class are in the `prototype` of the constructor. For instance, `HTMLDocument.prototype` has methods for documents.
Як відомо, методи класу знаходяться в `prototype` конструктора. Наприклад, `HTMLDocument.prototype` має методи документів.

Also, there's a reference to the constructor function inside the `prototype`:
Також є посилання на функцію конструктора всередині `prototype`:

```js run
alert(HTMLDocument.prototype.constructor === HTMLDocument); // true
```

To get a name of the class as a string, we can use `constructor.name`. Let's do it for the whole `document` prototype chain, till class `Node`:
Щоб отримати назву класу як рядок, ми можемо використовувати `constructor.name`. Давайте зробимо це для всього прототипного ланцюга `document` аж до класу` Node`:

```js run
alert(HTMLDocument.prototype.constructor.name); // HTMLDocument
alert(HTMLDocument.prototype.__proto__.constructor.name); // Document
alert(HTMLDocument.prototype.__proto__.__proto__.constructor.name); // Node
```

That's the hierarchy.
Це ієрархія.

We also could examine the object using `console.dir(document)` and see these names by opening `__proto__`. The console takes them from `constructor` internally.
Ми також можемо розглянути об’єкт за допомогою `console.dir(document)` і побачити ці назви, відкриваючи `__proto__`.Консоль браузера під капотом бере їх з `constructor`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 4

---

# Where's the "document" in the hierarchy?
# Де "document" в ієрархії?

Which class does the `document` belong to?
До якого класу належить `document`?

What's its place in the DOM hierarchy?
Де його місце в ієрархії DOM?

Does it inherit from `Node` or `Element`, or maybe `HTMLElement`?
Він успадковує від `Node` чи `Element`, або, можливо, `HTMLElement`?
Loading

0 comments on commit 0925650

Please sign in to comment.