diff --git a/2-ui/1-document/05-basic-dom-node-properties/2-lastchild-nodetype-inline/solution.md b/2-ui/1-document/05-basic-dom-node-properties/2-lastchild-nodetype-inline/solution.md index 52c34640a..4929cfbdd 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/2-lastchild-nodetype-inline/solution.md +++ b/2-ui/1-document/05-basic-dom-node-properties/2-lastchild-nodetype-inline/solution.md @@ -1,8 +1,8 @@ -There's a catch here. +Тут є пастка. -At the time of ` diff --git a/2-ui/1-document/05-basic-dom-node-properties/2-tree-info/task.md b/2-ui/1-document/05-basic-dom-node-properties/2-tree-info/task.md index f2d9edc67..a904dde1b 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/2-tree-info/task.md +++ b/2-ui/1-document/05-basic-dom-node-properties/2-tree-info/task.md @@ -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 `
  • ` shows: +Напишіть код, який для кожного `
  • ` показує: -1. What's the text inside it (without the subtree) -2. The number of nested `
  • ` -- all descendants, including the deeply nested ones. +1. Текст всередині вузла (без піддерева) +2. Кількість вкладених `
  • ` -- всіх нащадків, включаючи глибоко вкладені. [demo src="solution"] diff --git a/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/solution.md b/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/solution.md index 32900a789..4734fb006 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/solution.md +++ b/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/solution.md @@ -1,4 +1,4 @@ -The answer: **`BODY`**. +Відповідь: **`BODY`**. ```html run ``` -What's going on step by step: +Що відбувається крок за кроком: -1. The content of `` is replaced with the comment. The comment is ``, 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.tagName == "BODY"`. Як ми пам’ятаємо, `tagName` завжди пишеться великими літерами в HTML. +2. Коментар зараз є єдиним дочірнім вузлом, тому ми отримуємо його в `body.firstChild`. +3. Властивість коментаря `data` -- це його вміст (всередині ``): `"BODY"`. diff --git a/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/task.md b/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/task.md index efe50b48f..b16ff15b5 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/task.md +++ b/2-ui/1-document/05-basic-dom-node-properties/3-tag-in-comment/task.md @@ -2,9 +2,9 @@ importance: 3 --- -# Tag in comment +# Тег у коментарі -What does this code show? +Що показує цей код? ```html ``` diff --git a/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/solution.md b/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/solution.md index cb9456717..2d06ef23a 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/solution.md +++ b/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/solution.md @@ -1,33 +1,33 @@ -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 @@ -35,6 +35,6 @@ 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`. diff --git a/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/task.md b/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/task.md index de266c6ae..e855ffedc 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/task.md +++ b/2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/task.md @@ -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`? diff --git a/2-ui/1-document/05-basic-dom-node-properties/article.md b/2-ui/1-document/05-basic-dom-node-properties/article.md index b1d6486f4..492c178ea 100644 --- a/2-ui/1-document/05-basic-dom-node-properties/article.md +++ b/2-ui/1-document/05-basic-dom-node-properties/article.md @@ -1,60 +1,60 @@ -# Node properties: type, tag and contents +# Властивості вузлів: тип, тег та вміст -Let's get a more in-depth look at DOM nodes. +Давайте тепер більш уважно подивимося на вузли DOM. -In this chapter we'll see more into what they are and learn their most used properties. +У цьому розділі ми більше розглянемо те, чим вони являються та вивчаємо їх найбільш використані властивості. -## DOM node classes +## Класи DOM вузлів -Different DOM nodes may have different properties. For instance, an element node corresponding to tag `` has link-related properties, and the one corresponding to `` has input-related properties and so on. Text nodes are not the same as element nodes. But there are also common properties and methods between all of them, because all classes of DOM nodes form a single hierarchy. +Різні вузли DOM можуть мати різні властивості. Наприклад, вузол-елемент, що відповідає тегу ``, має властивості, які пов’язані з посиланням, а той вузол-елемент, що відповідає `` має властивості, пов’язані з полем введенням, тощо.Текстові вузли не такі, як вузли елементів. Але існують також загальні властивості та методи між усіма з усіма, оскільки всі класи вузлів DOM утворюють єдину ієрархію. -Each DOM node belongs to the corresponding built-in class. +Кожен вузол DOM належить до відповідного вбудованого класу. -The root of the hierarchy is [EventTarget](https://dom.spec.whatwg.org/#eventtarget), that is inherited by [Node](http://dom.spec.whatwg.org/#interface-node), and other DOM nodes inherit from it. +Коренем ієрархії є [EventTarget](https://dom.spec.whatwg.org/#eventtarget), від нього успадковується [Node](http://dom.spec.whatwg.org/#interface-node), а інші вузли DOM успадкують вже від нього. -Here's the picture, explanations to follow: +Ось рисунок, на якому слідує пояснення: ![](dom-class-hierarchy.svg) -The classes are: +Класи: -- [EventTarget](https://dom.spec.whatwg.org/#eventtarget) -- is the root "abstract" class. Objects of that class are never created. It serves as a base, so that all DOM nodes support so-called "events", we'll study them later. -- [Node](http://dom.spec.whatwg.org/#interface-node) -- is also an "abstract" class, serving as a base for DOM nodes. It provides the core tree functionality: `parentNode`, `nextSibling`, `childNodes` and so on (they are getters). Objects of `Node` class are never created. But there are concrete node classes that inherit from it, namely: `Text` for text nodes, `Element` for element nodes and more exotic ones like `Comment` for comment nodes. -- [Element](http://dom.spec.whatwg.org/#interface-element) -- is a base class for DOM elements. It provides element-level navigation like `nextElementSibling`, `children` and searching methods like `getElementsByTagName`, `querySelector`. A browser supports not only HTML, but also XML and SVG. The `Element` class serves as a base for more specific classes: `SVGElement`, `XMLElement` and `HTMLElement`. -- [HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) -- is finally the basic class for all HTML elements. It is inherited by concrete HTML elements: - - [HTMLInputElement](https://html.spec.whatwg.org/multipage/forms.html#htmlinputelement) -- the class for `` elements, - - [HTMLBodyElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlbodyelement) -- the class for `` elements, - - [HTMLAnchorElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlanchorelement) -- the class for `` elements, - - ...and so on. +- [EventTarget](https://dom.spec.whatwg.org/#eventtarget) -- це кореневий "абстрактний" клас. Об’єкти цього класу ніколи не створюються. Він служить основою, тому всі вузли DOM підтримують так звані "події", які ми розглянемо пізніше. +- [Node](http://dom.spec.whatwg.org/#interface-node) -- це також "абстрактний" клас, що служить базою для вузлів DOM. Він забезпечує основну функціональність дерева: `parentNode`, `nextSibling`, `childNodes` і так далі (це гетери). Об’єкти класу `Node` ніколи не створюються. Але є конкретні класи вузлів, які успадковуються від нього, а саме: `Text` для текстових вузлів, `Element` для вузлів-елементів та більш екзотичні, такі як `Comment` для вузлів-коментарів. +- [Element](http://dom.spec.whatwg.org/#interface-element) -- це базовий клас для елементів DOM. Він забезпечує навігацію на рівні елементів, таку як `nextElementSibling`, `children` та пошукові методи, такі як `getElementsByTagName`, `querySelector`. Браузер підтримує не тільки HTML, але й XML та SVG. Клас `Element` служить базою для більш конкретних класів: `SVGElement`, `XMLElement` та `HTMLElement`.. +- [HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) -- це, нарешті, основний клас для всіх елементів HTML. Він успадковується конкретними елементами HTML: + - [HTMLInputElement](https://html.spec.whatwg.org/multipage/forms.html#htmlinputelement) -- це клас для `` елементів, + - [HTMLBodyElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlbodyelement) -- це клас для `` елементів, + - [HTMLAnchorElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlanchorelement) -- це клас для `` елементів, + - ...і так далі. -There are many other tags with their own classes that may have specific properties and methods, while some elements, such as ``, `
    `, `
    ` do not have any specific properties, so they are instances of `HTMLElement` class. +Є багато інших тегів з власними класами, які можуть мати певні властивості та методи, а деякі елементи, такі як ``, `
    `, `
    ` не мають конкретних властивостей, тому вони є екземплярами класу `HTMLElement`. -So, the full set of properties and methods of a given node comes as the result of the inheritance. +Отже, повний набір властивостей та методів даного вузла надходить як результат наслідування. -For example, let's consider the DOM object for an `` element. It belongs to [HTMLInputElement](https://html.spec.whatwg.org/multipage/forms.html#htmlinputelement) class. +Наприклад, давайте розглянемо об’єкт DOM для елемента ``. Він належить до класу [HTMLInputElement](https://html.spec.whatwg.org/multipage/forms.html#htmlinputelement). -It gets properties and methods as a superposition of (listed in inheritance order): +Він отримує властивості та методи як накладення (перераховано в порядоку наслідування): -- `HTMLInputElement` -- this class provides input-specific properties, -- `HTMLElement` -- it provides common HTML element methods (and getters/setters), -- `Element` -- provides generic element methods, -- `Node` -- provides common DOM node properties, -- `EventTarget` -- gives the support for events (to be covered), -- ...and finally it inherits from `Object`, so "plain object" methods like `hasOwnProperty` are also available. +- `HTMLInputElement` -- цей клас забезпечує специфічні властивості введення, +- `HTMLElement` -- цей клас забезпечує загальні методи HTML-елементів (і гетери/сетери), +- `Element` -- забезпечує загальні методи елемента, +- `Node` -- забезпечує спільні властивості DOM вузлів, +- `EventTarget` -- дає підтримку подій (будуть розглянуті), +- ... і, нарешті, цей клас наслідує `Object`, тому "прості методи об’єкта" такими є, наприклад, `hasOwnProperty` також доступні. -To see the DOM node class name, we can recall that an object usually has the `constructor` property. It references the class constructor, and `constructor.name` is its name: +Щоб побачити назву класу DOM вузла, ми можемо згадати, що об’єкт, як правило, має властивість `constructor`. Вона посилається на конструктор класу, а `constructor.name` -- це його назва: ```js run alert( document.body.constructor.name ); // HTMLBodyElement ``` -...Or we can just `toString` it: +...Або ми можемо просто викликати `toString`: ```js run alert( document.body ); // [object HTMLBodyElement] ``` -We also can use `instanceof` to check the inheritance: +Ми також можемо використовувати `instanceof`, щоб перевірити наслідування: ```js run alert( document.body instanceof HTMLBodyElement ); // true @@ -64,38 +64,38 @@ alert( document.body instanceof Node ); // true alert( document.body instanceof EventTarget ); // true ``` -As we can see, DOM nodes are regular JavaScript objects. They use prototype-based classes for inheritance. +Як ми бачимо, вузли DOM є звичайними об’єктами JavaScript. Вони використовують класи з прототипів для наслідування. -That's also easy to see by outputting an element with `console.dir(elem)` in a browser. There in the console you can see `HTMLElement.prototype`, `Element.prototype` and so on. +Це також легко бачити, якщо вивести елемент за допомогою `console.dir(elem)` у браузері. Там в консолі ви можете побачити `HTMLElement.prototype`, `Element.prototype` і так далі. -```smart header="`console.dir(elem)` versus `console.log(elem)`" -Most browsers support two commands in their developer tools: `console.log` and `console.dir`. They output their arguments to the console. For JavaScript objects these commands usually do the same. +```smart header="`console.dir(elem)` проти `console.log(elem)`" +Більшість браузерів підтримують дві команди у своїх інструментах розробника: `console.log` та `console.dir`. Вони виводять свої аргументи в консоль. Для об’єктів JavaScript ці команди зазвичай роблять те ж саме. -But for DOM elements they are different: +Але для DOM елементів вони різні: -- `console.log(elem)` shows the element DOM tree. -- `console.dir(elem)` shows the element as a DOM object, good to explore its properties. +- `console.log(elem)` показує елемент DOM дерева. +- `console.dir(elem)` показує елемент як об’єкт DOM, це добре для того, щоб вивчити його властивості. -Try it on `document.body`. +Спробуйте це на `document.body`. ``` -````smart header="IDL in the spec" -In the specification, DOM classes aren't described by using JavaScript, but a special [Interface description language](https://en.wikipedia.org/wiki/Interface_description_language) (IDL), that is usually easy to understand. +````smart header="Специфікація IDL" +У специфікації, класи DOM описані не за допомогою JavaScript, а спеціальною [мовою опису інтерфейсу](https://uk.wikipedia.org/wiki/Мова_опису_інтерфейсів)(IDL), яку зазвичай легко зрозуміти. -In IDL all properties are prepended with their types. For instance, `DOMString`, `boolean` and so on. +У IDL всі властивості призводять до їх типів. Наприклад, `DOMString`, `boolean` тощо. -Here's an excerpt from it, with comments: +Ось витяг з цієї специфікації, з коментарями: ```js // Define HTMLInputElement *!* -// The colon ":" means that HTMLInputElement inherits from HTMLElement +// Двакрапка ":" означає, що HTMLInputElement наслідується від HTMLElement */!* interface HTMLInputElement: HTMLElement { - // here go properties and methods of elements + // тут визначаються всі властивості та методи елементів *!* - // "DOMString" means that the value of a property is a string + // "DOMString" означає, що значенням властивості є рядок */!* attribute DOMString accept; attribute DOMString alt; @@ -103,12 +103,12 @@ interface HTMLInputElement: HTMLElement { attribute DOMString value; *!* - // boolean value property (true/false) + // булева властивість (true/false) attribute boolean autofocus; */!* ... *!* - // now the method: "void" means that the method returns no value + // тепер метод: "void" означає, що метод не повертає значення */!* void select(); ... @@ -116,95 +116,95 @@ interface HTMLInputElement: HTMLElement { ``` ```` -## The "nodeType" property +## Властивість "nodeType" -The `nodeType` property provides one more, "old-fashioned" way to get the "type" of a DOM node. +Властивість `nodeType` надає ще один, "старомодний" спосіб отримати "тип" DOM вузла. -It has a numeric value: -- `elem.nodeType == 1` for element nodes, -- `elem.nodeType == 3` for text nodes, -- `elem.nodeType == 9` for the document object, -- there are few other values in [the specification](https://dom.spec.whatwg.org/#node). +Він має числове значення: +- `elem.nodeType == 1` для вузлів-елементів, +- `elem.nodeType == 3` для текстових вузлів, +- `elem.nodeType == 9` для об’єкта документа, +- є кілька інших значень у [специфікації](https://dom.spec.whatwg.org/#node). -For instance: +Наприклад: ```html run ``` -In modern scripts, we can use `instanceof` and other class-based tests to see the node type, but sometimes `nodeType` may be simpler. We can only read `nodeType`, not change it. +У сучасних скриптах, щоб побачити тип вузла, ми можемо використовувати `instanceof` та інші тести на основі класів, але іноді використовувати `nodeType` простіше. Ми можемо лише читати `nodeType`, а не змінювати його. -## Tag: nodeName and tagName +## Тег: nodeName та tagName -Given a DOM node, we can read its tag name from `nodeName` or `tagName` properties: +Маючи вузол DOM, ми можемо прочитати назву тега з властивостей `nodeName` або `tagName`: -For instance: +Наприклад: ```js run alert( document.body.nodeName ); // BODY alert( document.body.tagName ); // BODY ``` -Is there any difference between `tagName` and `nodeName`? +Чи існує різниця між `tagName` і `nodeName`? -Sure, the difference is reflected in their names, but is indeed a bit subtle. +Звичайно, різниця відображається у їх іменах, але вдійсності є трохи тонкою. -- The `tagName` property exists only for `Element` nodes. -- The `nodeName` is defined for any `Node`: - - for elements it means the same as `tagName`. - - for other node types (text, comment, etc.) it has a string with the node type. +- Властивість `tagName` існує лише для `Element` вузлів. +- `nodeName` визначається для будь-якого `Node`: + - для елементів це означає те ж саме, що і `tagName`. + - для інших типів вузлів (текст, коментар тощо) він має рядок з типом вузла. -In other words, `tagName` is only supported by element nodes (as it originates from `Element` class), while `nodeName` can say something about other node types. +Іншими словами, `tagName` підтримується лише вузлами елементів (оскільки вони походять від класу `Element`), а `nodeName` може сказати щось про інші типи вузлів. -For instance, let's compare `tagName` and `nodeName` for the `document` and a comment node: +Наприклад, давайте порівнюємо `tagName` and `nodeName` для вузла-документа та коментаря: ```html run ``` -If we only deal with elements, then we can use both `tagName` and `nodeName` - there's no difference. +Якщо ми маємо справу лише з елементами, то ми можемо використовувати як `tagName`, так і `nodeName` -- немає ніякої різниці. -```smart header="The tag name is always uppercase except in XML mode" -The browser has two modes of processing documents: HTML and XML. Usually the HTML-mode is used for webpages. XML-mode is enabled when the browser receives an XML-document with the header: `Content-Type: application/xml+xhtml`. +```smart header="Назва тегів завжди написана великими літерами, за винятком режиму XML" +Браузер має два режиму обробки документів: HTML та XML. Зазвичай HTML-режим використовується для веб-сторінок. XML-режим вмикається, коли браузер отримує XML-документ за допомогою заголовка: `Content-Type: application/xml+xhtml`. -In HTML mode `tagName/nodeName` is always uppercased: it's `BODY` either for `` or ``. +У режимі HTML `tagName/nodeName` завжди пишуться великими літерами: це `BODY` як для ``, так і для ``. -In XML mode the case is kept "as is". Nowadays XML mode is rarely used. +У режимі XML регістр літер зберігається "як є". В даний час XML режим рідко використовується. ``` -## innerHTML: the contents +## innerHTML: вміст -The [innerHTML](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin) property allows to get the HTML inside the element as a string. +Властивість [innerHTML](https://w3c.github.io/dom-parsing/#the-innerhtml-mixin) дозволяє отримати HTML всередині елемента як рядок. -We can also modify it. So it's one of the most powerful ways to change the page. +Ми також можемо це змінити. Отже, це один з найпотужніших способів зміни сторінку. -The example shows the contents of `document.body` and then replaces it completely: +На прикладі показано вміст `document.body` який потім повністю замінюється. ```html run @@ -212,88 +212,88 @@ The example shows the contents of `document.body` and then replaces it completel
    A div
    ``` -We can try to insert invalid HTML, the browser will fix our errors: +Ми можемо спробувати вставити невалідний HTML, браузер виправить наші помилки: ```html run ``` -```smart header="Scripts don't execute" -If `innerHTML` inserts a ` ``` -**Beware: unlike `innerHTML`, writing to `outerHTML` does not change the element. Instead, it replaces it in the DOM.** +**Остерігайтеся: на відміну від `innerHTML`, написання до `outerHTML` не змінює елемент. Замість цього він замінює його в DOM.** -Yeah, sounds strange, and strange it is, that's why we make a separate note about it here. Take a look. +Так, це звучить дивно, так воно і є, ось тому ми робимо окрему примітку про це тут. Поглянь. -Consider the example: +Розглянемо приклад: ```html run -
    Hello, world!
    +
    Привіт, світ!
    ``` -Looks really odd, right? +Виглядає дуже дивно, вірно? -In the line `(*)` we replaced `div` with `

    A new element

    `. In the outer document (the DOM) we can see the new content instead of the `
    `. But, as we can see in line `(**)`, the value of the old `div` variable hasn't changed! +У рядку `(*)` ми замінили `div` на `

    Новий елемент

    `. У зовнішньому документі (DOM) ми можемо побачити новий вміст замість `
    `. Але, як ми можемо бачити в рядку `(**)`, значення старого `div` не змінилося! -The `outerHTML` assignment does not modify the DOM element (the object referenced by, in this case, the variable 'div'), but removes it from the DOM and inserts the new HTML in its place. +Присвоєння `outerHTML` не змінює елемент DOM (об’єкт, на який посилається, у цьому випадку змінний 'div'), але його видаляє з DOM та вставляє новий HTML у своєму місці. -So what happened in `div.outerHTML=...` is: -- `div` was removed from the document. -- Another piece of HTML `

    A new element

    ` was inserted in its place. -- `div` still has its old value. The new HTML wasn't saved to any variable. +Отже, в `div.outerHTML=...` сталося наступне: +- `div` був видалений з документа. +- Інший шматок HTML `

    Новий елемент

    ` був вставлений на його місце. +- `div` ще має своє старе значення. Новий HTML не був збережений для будь-якої змінної. -It's so easy to make an error here: modify `div.outerHTML` and then continue to work with `div` as if it had the new content in it. But it doesn't. Such thing is correct for `innerHTML`, but not for `outerHTML`. +Тут так легко зробити помилку: змініть `div.outerHTML`, а потім продовжуйте працювати з `div` так, наче від має новий вміст у собі. Але це не так. Така річ є правильною для `innerHTML`, але не для `outerHTML`. -We can write to `elem.outerHTML`, but should keep in mind that it doesn't change the element we're writing to ('elem'). It puts the new HTML in its place instead. We can get references to the new elements by querying the DOM. +Ми можемо записати в `elem.outerHTML`, але слід пам’ятати, що це не змінює елемент, в який ми пишемо ('elem'). Це вставить замість цього новий HTML. Ми можемо отримати посилання на нові елементи, запитуючи DOM. -## nodeValue/data: text node content +## nodeValue/data: вміст тексту вузла -The `innerHTML` property is only valid for element nodes. +Властивість `innerHTML` існує лише для вузлів-елементів. -Other node types, such as text nodes, have their counterpart: `nodeValue` and `data` properties. These two are almost the same for practical use, there are only minor specification differences. So we'll use `data`, because it's shorter. +Інші типи вузлів, такі як текстові вузли, мають свій аналог: `nodeValue` і `data` властивості. Ці дві властивості майже однакові для практичного використання, є лише незначні відмінності в специфікації. Таким чином, ми будемо використовувати `data`, тому що це коротше. -An example of reading the content of a text node and a comment: +Приклад читання вмісту текстового вузла та коментаря: ```html run height="50" - Hello - + Привіт + ``` -For text nodes we can imagine a reason to read or modify them, but why comments? +Для текстових вузлів ми можемо уявити собі причину читати або змінити їх, але чому коментарі? -Sometimes developers embed information or template instructions into HTML in them, like this: +Іноді розробники вбудовують інформацію або інструкції в шаблон HTML, як наприклад: ```html -
    Welcome, Admin!
    +
    Ласкаво просимо, Адмін!
    ``` -...Then JavaScript can read it from `data` property and process embedded instructions. +...Тоді JavaScript може прочитати його з `data` властивості та обробити вбудовані інструкції. -## textContent: pure text +## textContent: чистий текст -The `textContent` provides access to the *text* inside the element: only text, minus all ``. +`textContent` надає доступ до *тексту* всередині елемента: тільки текст, мінус всі `<теги>`. -For instance: +Наприклад: ```html run
    -

    Headline!

    -

    Martians attack people!

    +

    Заголовок!

    +

    Марсіанці нападають на людей!

    ``` -As we can see, only text is returned, as if all `` were cut out, but the text in them remained. +Як ми бачимо, повертається лише текст, як ніби всі `` були вирізані, але текст у них залишився. -In practice, reading such text is rarely needed. +На практиці читання такого тексту рідко потрібне. -**Writing to `textContent` is much more useful, because it allows to write text the "safe way".** +**Запис в `textContent` набагато корисніше, тому що це дозволяє записати текст "безпечним способом".** -Let's say we have an arbitrary string, for instance entered by a user, and want to show it. +Скажімо, у нас є довільний рядок, наприклад той, що ввів користувач, і який він хочете показати. -- With `innerHTML` we'll have it inserted "as HTML", with all HTML tags. -- With `textContent` we'll have it inserted "as text", all symbols are treated literally. +- З `innerHTML` ми його вставили "як HTML", з усіма HTML-тегами. +- З `textContent` ми вставимо це "як текст", всі символи обробляються буквально. -Compare the two: +Порівняйте ці два підходи: ```html run
    ``` -1. The first `
    ` gets the name "as HTML": all tags become tags, so we see the bold name. -2. The second `
    ` gets the name "as text", so we literally see `Winnie-the-Pooh!`. +1. Перший `
    ` отримує назву "як HTML": всі теги стають тегами, тому ми бачимо назву жирним шрифтом. +2. Другий `
    ` отримує назву "як текст", тому ми буквально бачимо `Вінні Пух!`. -In most cases, we expect the text from a user, and want to treat it as text. We don't want unexpected HTML in our site. An assignment to `textContent` does exactly that. +У більшості випадків ми очікуємо отримати текст від користувача, і хочем працювати з ним як з текстом. Ми не хочемо несподіваного HTML на нашому сайті. Присвоєння в `textContent` робить саме це. -## The "hidden" property +## Властивість "hidden" -The "hidden" attribute and the DOM property specifies whether the element is visible or not. +Атрибут "hidden" та властивість DOM визначає, чи видно елемент чи ні. -We can use it in HTML or assign it using JavaScript, like this: +Ми можемо використовувати її в HTML або призначити її за допомогою JavaScript, як наприклад: ```html run height="80" -
    Both divs below are hidden
    +
    Обидва div нижче приховані
    - + -
    JavaScript assigned the property "hidden"
    +
    JavaScript призначив властивість "hidden"
    ``` -Technically, `hidden` works the same as `style="display:none"`. But it's shorter to write. +Технічно, `hidden` працює так само, як `style="display:none"`. Але це коротше писати. -Here's a blinking element: +Ось блимаючий елемент: ```html run height=50 -
    A blinking element
    +
    Блимаючий елемент
    ``` -## More properties +## Більше властивостей -DOM elements also have additional properties, in particular those that depend on the class: +Елементи DOM також мають додаткові властивості, зокрема, ті, які залежать від класу: -- `value` -- the value for ``, `