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..96d214544 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. +Há uma pegadinha aqui. -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..a5627022e 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 +# Contar descendentes -There's a tree structured as nested `ul/li`. +Há uma árvore estruturada como `ul/li` aninhados. -Write the code that for each `
  • ` shows: +Escreva o código que, para cada `
  • `, mostra: -1. What's the text inside it (without the subtree) -2. The number of nested `
  • ` -- all descendants, including the deeply nested ones. +1. Qual é o texto dentro dele (sem a subárvore) +2. O número de `
  • ` aninhados -- todos os descendentes, incluindo os mais profundamente aninhados. [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..600dc20fd 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`**. +A resposta: **`BODY`**. ```html run ``` -What's going on step by step: +O que está acontecendo, passo a passo: -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. O conteúdo de `` é substituído pelo comentário. O comentário é ``, porque `body.tagName == "BODY"`. Como lembramos, `tagName` é sempre em maiúsculas em HTML. +2. O comentário agora é o único nó filho, então o obtemos em `body.firstChild`. +3. A propriedade `data` do comentário é o seu conteúdo (dentro de ``): `"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..cd8dad825 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 +# Tag em comentário -What does this code show? +O que este código mostra? ```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..74bed8401 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: +Podemos ver a qual classe ele pertence exibindo-o, assim: ```js run alert(document); // [object HTMLDocument] ``` -Or: +Ou: ```js run alert(document.constructor.name); // HTMLDocument ``` -So, `document` is an instance of `HTMLDocument` class. +Então, `document` é uma instância da classe `HTMLDocument`. -What's its place in the hierarchy? +Qual é o seu lugar na hierarquia? -Yeah, we could browse the specification, but it would be faster to figure out manually. +Sim, poderíamos navegar pela especificação, mas seria mais rápido descobrir manualmente. -Let's traverse the prototype chain via `__proto__`. +Vamos percorrer a cadeia de protótipos via `__proto__`. -As we know, methods of a class are in the `prototype` of the constructor. For instance, `HTMLDocument.prototype` has methods for documents. +Como sabemos, os métodos de uma classe estão no `prototype` do construtor. Por exemplo, `HTMLDocument.prototype` tem métodos para documentos. -Also, there's a reference to the constructor function inside the `prototype`: +Além disso, há uma referência à função construtora dentro do `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`: +Para obter o nome da classe como uma string, podemos usar `constructor.name`. Vamos fazer isso para toda a cadeia de protótipos do `document`, até a classe `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. +Essa é a hierarquia. -We also could examine the object using `console.dir(document)` and see these names by opening `__proto__`. The console takes them from `constructor` internally. +Também poderíamos examinar o objeto usando `console.dir(document)` e ver esses nomes abrindo `__proto__`. O console obtém esses nomes internamente a partir de `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..40dedd0d9 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? +# Qual é o lugar do "document" na hierarquia? -Which class does the `document` belong to? +A qual classe o `document` pertence? -What's its place in the DOM hierarchy? +Qual é o seu lugar na hierarquia do DOM? -Does it inherit from `Node` or `Element`, or maybe `HTMLElement`? +Ele herda de `Node` ou `Element`, ou talvez `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 99dde5bcd..a666d8102 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,81 +1,81 @@ -# Node properties: type, tag and contents +# Propriedades de nó: tipo, tag e conteúdo -Let's get a more in-depth look at DOM nodes. +Vamos dar uma olhada mais a fundo nos nós do DOM. -In this chapter we'll see more into what they are and learn their most used properties. +Neste capítulo vamos ver mais sobre o que eles são e aprender suas propriedades mais usadas. -## DOM node classes +## Classes de nó do 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. +Nós do DOM diferentes podem ter propriedades diferentes. Por exemplo, um nó de elemento correspondente à tag `` tem propriedades relacionadas a link, e o correspondente a `` tem propriedades relacionadas a input e assim por diante. Nós de texto não são iguais a nós de elemento. Mas também existem propriedades e métodos comuns entre todos eles, porque todas as classes de nós do DOM formam uma única hierarquia. -Each DOM node belongs to the corresponding built-in class. +Cada nó do DOM pertence à classe nativa correspondente. -The root of the hierarchy is [EventTarget](https://dom.spec.whatwg.org/#eventtarget), that is inherited by [Node](https://dom.spec.whatwg.org/#interface-node), and other DOM nodes inherit from it. +A raiz da hierarquia é [EventTarget](https://dom.spec.whatwg.org/#eventtarget), que é herdada por [Node](https://dom.spec.whatwg.org/#interface-node), e outros nós do DOM herdam dela. -Here's the picture, explanations to follow: +Aqui está a imagem, explicações a seguir: ![](dom-class-hierarchy.svg) -The classes are: +As classes são: -- [EventTarget](https://dom.spec.whatwg.org/#eventtarget) -- is the root "abstract" class for everything. +- [EventTarget](https://dom.spec.whatwg.org/#eventtarget) -- é a classe "abstrata" raiz para tudo. - 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. + Objetos dessa classe nunca são criados. Ela serve como base, para que todos os nós do DOM suportem os chamados "eventos", vamos estudá-los mais tarde. -- [Node](https://dom.spec.whatwg.org/#interface-node) -- is also an "abstract" class, serving as a base for DOM nodes. +- [Node](https://dom.spec.whatwg.org/#interface-node) -- também é uma classe "abstrata", servindo como base para nós do DOM. - 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 other classes that inherit from it (and so inherit the `Node` functionality). + Ela fornece a funcionalidade central de árvore: `parentNode`, `nextSibling`, `childNodes` e assim por diante (são getters). Objetos da classe `Node` nunca são criados. Mas existem outras classes que herdam dela (e assim herdam a funcionalidade de `Node`). -- [Document](https://dom.spec.whatwg.org/#interface-document), for historical reasons often inherited by `HTMLDocument` (though the latest spec doesn't dictate it) -- is a document as a whole. +- [Document](https://dom.spec.whatwg.org/#interface-document), por motivos históricos frequentemente herdada por `HTMLDocument` (embora a especificação mais recente não exija isso) -- é um documento como um todo. - The `document` global object belongs exactly to this class. It serves as an entry point to the DOM. + O objeto global `document` pertence exatamente a essa classe. Ele serve como ponto de entrada para o DOM. -- [CharacterData](https://dom.spec.whatwg.org/#interface-characterdata) -- an "abstract" class, inherited by: - - [Text](https://dom.spec.whatwg.org/#interface-text) -- the class corresponding to a text inside elements, e.g. `Hello` in `

    Hello

    `. - - [Comment](https://dom.spec.whatwg.org/#interface-comment) -- the class for comments. They are not shown, but each comment becomes a member of DOM. +- [CharacterData](https://dom.spec.whatwg.org/#interface-characterdata) -- uma classe "abstrata", herdada por: + - [Text](https://dom.spec.whatwg.org/#interface-text) -- a classe correspondente a um texto dentro de elementos, por exemplo, `Hello` em `

    Hello

    `. + - [Comment](https://dom.spec.whatwg.org/#interface-comment) -- a classe para comentários. Eles não são exibidos, mas cada comentário se torna um membro do DOM. -- [Element](https://dom.spec.whatwg.org/#interface-element) -- is the base class for DOM elements. +- [Element](https://dom.spec.whatwg.org/#interface-element) -- é a classe base para elementos do DOM. - It provides element-level navigation like `nextElementSibling`, `children` and searching methods like `getElementsByTagName`, `querySelector`. + Ela fornece navegação em nível de elemento como `nextElementSibling`, `children` e métodos de busca como `getElementsByTagName`, `querySelector`. - A browser supports not only HTML, but also XML and SVG. So the `Element` class serves as a base for more specific classes: `SVGElement`, `XMLElement` (we don't need them here) and `HTMLElement`. + Um navegador suporta não só HTML, mas também XML e SVG. Então a classe `Element` serve como base para classes mais específicas: `SVGElement`, `XMLElement` (não precisamos delas aqui) e `HTMLElement`. -- Finally, [HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) is the basic class for all HTML elements. We'll work with it most of the time. +- Finalmente, [HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) é a classe básica para todos os elementos HTML. Vamos trabalhar com ela na maior parte do tempo. - 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. + Ela é herdada por elementos HTML concretos: + - [HTMLInputElement](https://html.spec.whatwg.org/multipage/forms.html#htmlinputelement) -- a classe para elementos ``, + - [HTMLBodyElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlbodyelement) -- a classe para elementos ``, + - [HTMLAnchorElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlanchorelement) -- a classe para elementos ``, + - ...e assim por diante. -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. +Existem muitas outras tags com suas próprias classes que podem ter propriedades e métodos específicos, enquanto alguns elementos, como ``, `
    `, `
    `, não têm nenhuma propriedade específica, então são instâncias da classe `HTMLElement`. -So, the full set of properties and methods of a given node comes as the result of the chain of inheritance. +Então, o conjunto completo de propriedades e métodos de um determinado nó vem como resultado da cadeia de herança. -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. +Por exemplo, vamos considerar o objeto DOM para um elemento ``. Ele pertence à classe [HTMLInputElement](https://html.spec.whatwg.org/multipage/forms.html#htmlinputelement). -It gets properties and methods as a superposition of (listed in inheritance order): +Ele obtém propriedades e métodos como uma superposição de (listados na ordem de herança): -- `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` -- essa classe fornece propriedades específicas de input, +- `HTMLElement` -- ela fornece métodos comuns de elementos HTML (e getters/setters), +- `Element` -- fornece métodos genéricos de elemento, +- `Node` -- fornece propriedades comuns de nós do DOM, +- `EventTarget` -- dá suporte para eventos (a ser coberto), +- ...e finalmente ela herda de `Object`, então métodos de "objeto simples" como `hasOwnProperty` também estão disponíveis. -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: +Para ver o nome da classe de um nó do DOM, podemos lembrar que um objeto geralmente tem a propriedade `constructor`. Ela referencia o construtor da classe, e `constructor.name` é seu nome: ```js run alert( document.body.constructor.name ); // HTMLBodyElement ``` -...Or we can just `toString` it: +...Ou podemos simplesmente usar `toString` nele: ```js run alert( document.body ); // [object HTMLBodyElement] ``` -We also can use `instanceof` to check the inheritance: +Também podemos usar `instanceof` para checar a herança: ```js run alert( document.body instanceof HTMLBodyElement ); // true @@ -85,38 +85,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. +Como podemos ver, nós do DOM são objetos JavaScript comuns. Eles usam classes baseadas em protótipo para herança. -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. +Isso também é fácil de ver exibindo um elemento com `console.dir(elem)` num navegador. Lá no console você pode ver `HTMLElement.prototype`, `Element.prototype` e assim por diante. ```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. +A maioria dos navegadores suporta dois comandos em suas ferramentas de desenvolvedor: `console.log` e `console.dir`. Eles exibem seus argumentos no console. Para objetos JavaScript, esses comandos geralmente fazem a mesma coisa. -But for DOM elements they are different: +Mas para elementos do DOM eles são diferentes: -- `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)` mostra a árvore DOM do elemento. +- `console.dir(elem)` mostra o elemento como um objeto DOM, bom para explorar suas propriedades. -Try it on `document.body`. +Experimente em `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 na especificação" +Na especificação, classes do DOM não são descritas usando JavaScript, mas uma linguagem especial de descrição de interface, [Interface description language](https://en.wikipedia.org/wiki/Interface_description_language) (IDL), que geralmente é fácil de entender. -In IDL all properties are prepended with their types. For instance, `DOMString`, `boolean` and so on. +Em IDL, todas as propriedades vêm precedidas pelos seus tipos. Por exemplo, `DOMString`, `boolean` e assim por diante. -Here's an excerpt from it, with comments: +Aqui está um trecho dela, com comentários: ```js // Define HTMLInputElement *!* -// The colon ":" means that HTMLInputElement inherits from HTMLElement +// Os dois-pontos ":" significam que HTMLInputElement herda de HTMLElement */!* interface HTMLInputElement: HTMLElement { - // here go properties and methods of elements + // aqui vão propriedades e métodos de elementos *!* - // "DOMString" means that the value of a property is a string + // "DOMString" significa que o valor de uma propriedade é uma string */!* attribute DOMString accept; attribute DOMString alt; @@ -124,12 +124,12 @@ interface HTMLInputElement: HTMLElement { attribute DOMString value; *!* - // boolean value property (true/false) + // propriedade de valor booleano (true/false) attribute boolean autofocus; */!* ... *!* - // now the method: "void" means that the method returns no value + // agora o método: "void" significa que o método não retorna nenhum valor */!* void select(); ... @@ -137,95 +137,95 @@ interface HTMLInputElement: HTMLElement { ``` ```` -## The "nodeType" property +## A propriedade "nodeType" -The `nodeType` property provides one more, "old-fashioned" way to get the "type" of a DOM node. +A propriedade `nodeType` fornece mais uma forma, "à moda antiga", de obter o "tipo" de um nó do 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). +Ela tem um valor numérico: +- `elem.nodeType == 1` para nós de elemento, +- `elem.nodeType == 3` para nós de texto, +- `elem.nodeType == 9` para o objeto document, +- existem poucos outros valores [na especificação](https://dom.spec.whatwg.org/#node). -For instance: +Por exemplo: ```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. +Em scripts modernos, podemos usar `instanceof` e outros testes baseados em classe para ver o tipo do nó, mas às vezes `nodeType` pode ser mais simples. Só podemos ler `nodeType`, não alterá-lo. -## Tag: nodeName and tagName +## Tag: nodeName e tagName -Given a DOM node, we can read its tag name from `nodeName` or `tagName` properties: +Dado um nó do DOM, podemos ler o nome de sua tag a partir das propriedades `nodeName` ou `tagName`: -For instance: +Por exemplo: ```js run alert( document.body.nodeName ); // BODY alert( document.body.tagName ); // BODY ``` -Is there any difference between `tagName` and `nodeName`? +Existe alguma diferença entre `tagName` e `nodeName`? -Sure, the difference is reflected in their names, but is indeed a bit subtle. +Claro, a diferença se reflete em seus nomes, mas é de fato um pouco sutil. -- 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. +- A propriedade `tagName` existe só para nós `Element`. +- `nodeName` é definida para qualquer `Node`: + - para elementos significa o mesmo que `tagName`. + - para outros tipos de nó (texto, comentário, etc.) ela tem uma string com o tipo do nó. -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. +Em outras palavras, `tagName` é suportada só por nós de elemento (já que vem da classe `Element`), enquanto `nodeName` pode dizer algo sobre outros tipos de nó. -For instance, let's compare `tagName` and `nodeName` for the `document` and a comment node: +Por exemplo, vamos comparar `tagName` e `nodeName` para o `document` e um nó de comentário: ```html run ``` -If we only deal with elements, then we can use both `tagName` and `nodeName` - there's no difference. +Se só lidarmos com elementos, então podemos usar tanto `tagName` quanto `nodeName` - não há diferença. -```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="O nome da tag é sempre maiúsculo, exceto no modo XML" +O navegador tem dois modos de processar documentos: HTML e XML. Normalmente, o modo HTML é usado para páginas web. O modo XML é ativado quando o navegador recebe um documento XML com o cabeçalho: `Content-Type: application/xml+xhtml`. -In HTML mode `tagName/nodeName` is always uppercased: it's `BODY` either for `` or ``. +No modo HTML, `tagName/nodeName` é sempre maiúsculo: é `BODY` tanto para `` quanto para ``. -In XML mode the case is kept "as is". Nowadays XML mode is rarely used. +No modo XML, a caixa é mantida "como está". Hoje em dia o modo XML é raramente usado. ``` -## innerHTML: the contents +## innerHTML: o conteúdo -The [innerHTML](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin) property allows to get the HTML inside the element as a string. +A propriedade [innerHTML](https://w3c.github.io/DOM-Parsing/#the-innerhtml-mixin) permite obter o HTML dentro do elemento como uma string. -We can also modify it. So it's one of the most powerful ways to change the page. +Também podemos modificá-la. Então é uma das formas mais poderosas de mudar a página. -The example shows the contents of `document.body` and then replaces it completely: +O exemplo mostra o conteúdo de `document.body` e então o substitui completamente: ```html run @@ -233,71 +233,71 @@ 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: +Podemos tentar inserir HTML inválido, o navegador vai corrigir nossos erros: ```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.** +**Cuidado: diferente de `innerHTML`, escrever em `outerHTML` não muda o elemento. Em vez disso, o substitui no DOM.** -Yeah, sounds strange, and strange it is, that's why we make a separate note about it here. Take a look. +Sim, soa estranho, e é estranho mesmo, por isso fazemos uma observação separada sobre isso aqui. Dê uma olhada. -Consider the example: +Considere o exemplo: ```html run
    Hello, world!
    @@ -320,39 +320,39 @@ Consider the example: let div = document.querySelector('div'); *!* - // replace div.outerHTML with

    ...

    + // substitui div.outerHTML por

    ...

    */!* div.outerHTML = '

    A new element

    '; // (*) *!* - // Wow! 'div' is still the same! + // Uau! 'div' ainda é o mesmo! */!* alert(div.outerHTML); //
    Hello, world!
    (**) ``` -Looks really odd, right? +Parece bem estranho, não é? -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! +Na linha `(*)` substituímos `div` por `

    A new element

    `. No documento externo (o DOM) podemos ver o novo conteúdo no lugar do `
    `. Mas, como podemos ver na linha `(**)`, o valor da antiga variável `div` não mudou! -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. +A atribuição a `outerHTML` não modifica o elemento do DOM (o objeto referenciado, nesse caso, pela variável 'div'), mas o remove do DOM e insere o novo HTML no seu lugar. -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. +Então o que aconteceu em `div.outerHTML=...` foi: +- `div` foi removido do documento. +- Outro pedaço de HTML `

    A new element

    ` foi inserido no seu lugar. +- `div` ainda tem seu valor antigo. O novo HTML não foi salvo em nenhuma variável. -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`. +É muito fácil cometer um erro aqui: modificar `div.outerHTML` e depois continuar trabalhando com `div` como se ele tivesse o novo conteúdo nele. Mas não tem. Isso é correto para `innerHTML`, mas não para `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. +Podemos escrever em `elem.outerHTML`, mas devemos ter em mente que isso não muda o elemento em que estamos escrevendo ('elem'). Em vez disso, coloca o novo HTML no seu lugar. Podemos obter referências aos novos elementos consultando o DOM. -## nodeValue/data: text node content +## nodeValue/data: conteúdo de nó de texto -The `innerHTML` property is only valid for element nodes. +A propriedade `innerHTML` só é válida para nós de elemento. -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. +Outros tipos de nó, como nós de texto, têm sua contraparte: as propriedades `nodeValue` e `data`. Essas duas são quase iguais para uso prático, existem só pequenas diferenças de especificação. Então vamos usar `data`, porque é mais curto. -An example of reading the content of a text node and a comment: +Um exemplo de leitura do conteúdo de um nó de texto e um comentário: ```html run height="50" @@ -372,9 +372,9 @@ An example of reading the content of a text node and a comment: ``` -For text nodes we can imagine a reason to read or modify them, but why comments? +Para nós de texto podemos imaginar um motivo para ler ou modificá-los, mas por que comentários? -Sometimes developers embed information or template instructions into HTML in them, like this: +Às vezes os desenvolvedores incorporam informações ou instruções de template nos comentários do HTML, assim: ```html @@ -382,13 +382,13 @@ Sometimes developers embed information or template instructions into HTML in the ``` -...Then JavaScript can read it from `data` property and process embedded instructions. +...Então o JavaScript pode ler isso a partir da propriedade `data` e processar instruções incorporadas. -## textContent: pure text +## textContent: texto puro -The `textContent` provides access to the *text* inside the element: only text, minus all ``. +`textContent` fornece acesso ao *texto* dentro do elemento: só texto, menos todas as ``. -For instance: +Por exemplo: ```html run
    @@ -402,18 +402,18 @@ For instance: ``` -As we can see, only text is returned, as if all `` were cut out, but the text in them remained. +Como podemos ver, só o texto é retornado, como se todas as `` tivessem sido cortadas, mas o texto nelas permaneceu. -In practice, reading such text is rarely needed. +Na prática, ler esse tipo de texto raramente é necessário. -**Writing to `textContent` is much more useful, because it allows to write text the "safe way".** +**Escrever em `textContent` é muito mais útil, porque permite escrever texto de forma "segura".** -Let's say we have an arbitrary string, for instance entered by a user, and want to show it. +Digamos que temos uma string arbitrária, por exemplo digitada por um usuário, e queremos mostrá-la. -- 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. +- Com `innerHTML` vamos tê-la inserida "como HTML", com todas as tags HTML. +- Com `textContent` vamos tê-la inserida "como texto", todos os símbolos são tratados literalmente. -Compare the two: +Compare os dois: ```html run
    @@ -427,16 +427,16 @@ Compare the two: ``` -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. O primeiro `
    ` recebe o nome "como HTML": todas as tags se tornam tags, então vemos o nome em negrito. +2. O segundo `
    ` recebe o nome "como texto", então literalmente vemos `Winnie-the-Pooh!`. -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. +Na maioria dos casos, esperamos o texto de um usuário, e queremos tratá-lo como texto. Não queremos HTML inesperado no nosso site. Uma atribuição a `textContent` faz exatamente isso. -## The "hidden" property +## A propriedade "hidden" -The "hidden" attribute and the DOM property specifies whether the element is visible or not. +O atributo "hidden" e a propriedade do DOM especificam se o elemento está visível ou não. -We can use it in HTML or assign it using JavaScript, like this: +Podemos usá-lo em HTML ou atribuí-lo usando JavaScript, assim: ```html run height="80"
    Both divs below are hidden
    @@ -450,9 +450,9 @@ We can use it in HTML or assign it using JavaScript, like this: ``` -Technically, `hidden` works the same as `style="display:none"`. But it's shorter to write. +Tecnicamente, `hidden` funciona da mesma forma que `style="display:none"`. Mas é mais curto de escrever. -Here's a blinking element: +Aqui está um elemento piscando: ```html run height=50 @@ -463,16 +463,16 @@ Here's a blinking element: ``` -## More properties +## Mais propriedades -DOM elements also have additional properties, in particular those that depend on the class: +Elementos do DOM também têm propriedades adicionais, em particular aquelas que dependem da classe: -- `value` -- the value for ``, `