From c09bbc3f0a3e7c6adbffb2331cb97c594de23a5d Mon Sep 17 00:00:00 2001 From: Diogo Marciano Date: Sat, 21 Nov 2026 20:15:32 -0300 Subject: [PATCH 1/2] Translate 'Modifying the document' article to Portuguese Includes all 10 exercise subfolders. SVGs (before-prepend-append-after.svg, insert-adjacent.svg) contain only method-name/keyword identifiers, so left untouched. Co-Authored-By: Claude Sonnet 5 --- .../1-createtextnode-vs-innerhtml/solution.md | 6 +- .../1-createtextnode-vs-innerhtml/task.md | 4 +- .../10-clock-setinterval/solution.md | 20 +- .../solution.view/index.html | 16 +- .../source.view/index.html | 8 +- .../10-clock-setinterval/task.md | 6 +- .../11-append-to-list/solution.md | 4 +- .../11-append-to-list/task.md | 4 +- .../12-sort-table/solution.md | 14 +- .../12-sort-table/solution.view/index.html | 2 +- .../12-sort-table/source.view/index.html | 4 +- .../12-sort-table/task.md | 10 +- .../4-clear-elem/solution.md | 10 +- .../4-clear-elem/task.md | 12 +- .../5-why-aaa/solution.md | 10 +- .../07-modifying-document/5-why-aaa/task.md | 14 +- .../6-create-list/solution.md | 2 +- .../6-create-list/solution.view/index.html | 4 +- .../6-create-list/task.md | 16 +- .../build-tree-dom.view/index.html | 22 +- .../innerhtml.view/index.html | 20 +- .../7-create-object-tree/solution.md | 6 +- .../source.view/index.html | 40 +-- .../7-create-object-tree/task.md | 40 +-- .../8-tree-count/solution.md | 2 +- .../8-tree-count/solution.view/index.html | 34 +- .../8-tree-count/source.view/index.html | 32 +- .../8-tree-count/task.md | 8 +- .../9-calendar-table/solution.md | 14 +- .../9-calendar-table/solution.view/index.html | 20 +- .../9-calendar-table/source.view/index.html | 2 +- .../9-calendar-table/task.md | 12 +- .../07-modifying-document/article.md | 316 +++++++++--------- 33 files changed, 367 insertions(+), 367 deletions(-) diff --git a/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/solution.md b/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/solution.md index a38f01645..15724db5a 100644 --- a/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/solution.md +++ b/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/solution.md @@ -1,8 +1,8 @@ -Answer: **1 and 3**. +Resposta: **1 e 3**. -Both commands result in adding the `text` "as text" into the `elem`. +Ambos os comandos resultam em adicionar o `text` "como texto" dentro de `elem`. -Here's an example: +Aqui está um exemplo: ```html run height=80
diff --git a/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/task.md b/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/task.md index 40c75dff3..e99bacac5 100644 --- a/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/task.md +++ b/2-ui/1-document/07-modifying-document/1-createtextnode-vs-innerhtml/task.md @@ -4,9 +4,9 @@ importance: 5 # createTextNode vs innerHTML vs textContent -We have an empty DOM element `elem` and a string `text`. +Temos um elemento do DOM vazio `elem` e uma string `text`. -Which of these 3 commands will do exactly the same? +Qual destes 3 comandos vai fazer exatamente a mesma coisa? 1. `elem.append(document.createTextNode(text))` 2. `elem.innerHTML = text` diff --git a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md index 1414e90c1..436264909 100644 --- a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md +++ b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md @@ -1,6 +1,6 @@ -First, let's make HTML/CSS. +Primeiro, vamos fazer o HTML/CSS. -Each component of the time would look great in its own ``: +Cada componente da hora ficaria ótimo em seu próprio ``: ```html
@@ -8,9 +8,9 @@ Each component of the time would look great in its own ``:
``` -Also we'll need CSS to color them. +Também vamos precisar de CSS para colori-los. -The `update` function will refresh the clock, to be called by `setInterval` every second: +A função `update` vai atualizar o relógio, sendo chamada pelo `setInterval` a cada segundo: ```js function update() { @@ -32,15 +32,15 @@ function update() { } ``` -In the line `(*)` we every time check the current date. The calls to `setInterval` are not reliable: they may happen with delays. +Na linha `(*)` verificamos a data atual a cada vez. As chamadas a `setInterval` não são confiáveis: podem acontecer com atrasos. -The clock-managing functions: +As funções que gerenciam o relógio: ```js let timerId; -function clockStart() { // run the clock - if (!timerId) { // only set a new interval if the clock is not running +function clockStart() { // inicia o relógio + if (!timerId) { // só define um novo intervalo se o relógio não estiver em execução timerId = setInterval(update, 1000); } update(); // (*) @@ -52,6 +52,6 @@ function clockStop() { } ``` -Please note that the call to `update()` is not only scheduled in `clockStart()`, but immediately run in the line `(*)`. Otherwise the visitor would have to wait till the first execution of `setInterval`. And the clock would be empty till then. +Note que a chamada a `update()` não é apenas agendada em `clockStart()`, mas também executada imediatamente na linha `(*)`. Caso contrário, o visitante teria que esperar até a primeira execução do `setInterval`. E o relógio ficaria vazio até então. -Also it is important to set a new interval in `clockStart()` only when the clock is not running. Otherways clicking the start button several times would set multiple concurrent intervals. Even worse - we would only keep the `timerID` of the last interval, losing references to all others. Then we wouldn't be able to stop the clock ever again! Note that we need to clear the `timerID` when the clock is stopped in the line `(**)`, so that it can be started again by running `clockStart()`. +Também é importante definir um novo intervalo em `clockStart()` apenas quando o relógio não estiver em execução. Caso contrário, clicar no botão de início várias vezes definiria múltiplos intervalos simultâneos. Pior ainda - manteríamos apenas o `timerID` do último intervalo, perdendo as referências a todos os outros. Então nunca mais conseguiríamos parar o relógio! Note que precisamos limpar o `timerID` quando o relógio é parado na linha `(**)`, para que ele possa ser iniciado novamente ao executar `clockStart()`. diff --git a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html index 84ee26f19..ae9a2bf78 100644 --- a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html +++ b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html @@ -43,26 +43,26 @@ } function clockStart() { - // set a new interval only if the clock is stopped - // otherwise we would rewrite the timerID reference to the running interval and wouldn't be able to stop the clock ever again + // define um novo intervalo apenas se o relógio estiver parado + // caso contrário, reescreveríamos a referência timerID do intervalo em execução e nunca mais conseguiríamos parar o relógio if (!timerId) { timerId = setInterval(update, 1000); } - update(); // <-- start right now, don't wait 1 second till the first setInterval works + update(); // <-- começa agora mesmo, não espera 1 segundo até o primeiro setInterval funcionar } function clockStop() { clearInterval(timerId); - timerId = null; // <-- clear timerID to indicate that the clock has been stopped, so that it is possible to start it again in clockStart() + timerId = null; // <-- limpa o timerID para indicar que o relógio foi parado, para que seja possível iniciá-lo novamente em clockStart() } - - + + - - + + diff --git a/2-ui/1-document/07-modifying-document/10-clock-setinterval/source.view/index.html b/2-ui/1-document/07-modifying-document/10-clock-setinterval/source.view/index.html index ecf5df99a..d45d3cce2 100644 --- a/2-ui/1-document/07-modifying-document/10-clock-setinterval/source.view/index.html +++ b/2-ui/1-document/07-modifying-document/10-clock-setinterval/source.view/index.html @@ -2,11 +2,11 @@ - - + + - - + + diff --git a/2-ui/1-document/07-modifying-document/10-clock-setinterval/task.md b/2-ui/1-document/07-modifying-document/10-clock-setinterval/task.md index a1b53e337..4c7bc6ffb 100644 --- a/2-ui/1-document/07-modifying-document/10-clock-setinterval/task.md +++ b/2-ui/1-document/07-modifying-document/10-clock-setinterval/task.md @@ -2,10 +2,10 @@ importance: 4 --- -# Colored clock with setInterval +# Relógio colorido com setInterval -Create a colored clock like here: +Crie um relógio colorido como este: [iframe src="solution" height=60] -Use HTML/CSS for the styling, JavaScript only updates time in elements. +Use HTML/CSS para a estilização, o JavaScript só atualiza a hora nos elementos. diff --git a/2-ui/1-document/07-modifying-document/11-append-to-list/solution.md b/2-ui/1-document/07-modifying-document/11-append-to-list/solution.md index 4e77fb5cb..6044fccf6 100644 --- a/2-ui/1-document/07-modifying-document/11-append-to-list/solution.md +++ b/2-ui/1-document/07-modifying-document/11-append-to-list/solution.md @@ -1,7 +1,7 @@ -When we need to insert a piece of HTML somewhere, `insertAdjacentHTML` is the best fit. +Quando precisamos inserir um pedaço de HTML em algum lugar, `insertAdjacentHTML` é a melhor opção. -The solution: +A solução: ```js one.insertAdjacentHTML('afterend', '
  • 2
  • 3
  • '); diff --git a/2-ui/1-document/07-modifying-document/11-append-to-list/task.md b/2-ui/1-document/07-modifying-document/11-append-to-list/task.md index 543cd3e46..75fe0d43d 100644 --- a/2-ui/1-document/07-modifying-document/11-append-to-list/task.md +++ b/2-ui/1-document/07-modifying-document/11-append-to-list/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Insert the HTML in the list +# Insira o HTML na lista -Write the code to insert `
  • 2
  • 3
  • ` between two `
  • ` here: +Escreva o código para inserir `
  • 2
  • 3
  • ` entre dois `
  • ` aqui: ```html
      diff --git a/2-ui/1-document/07-modifying-document/12-sort-table/solution.md b/2-ui/1-document/07-modifying-document/12-sort-table/solution.md index 49243e8e3..e0437ea10 100644 --- a/2-ui/1-document/07-modifying-document/12-sort-table/solution.md +++ b/2-ui/1-document/07-modifying-document/12-sort-table/solution.md @@ -1,4 +1,4 @@ -The solution is short, yet may look a bit tricky, so here I provide it with extensive comments: +A solução é curta, mas pode parecer um pouco complicada, então aqui eu a apresento com comentários extensos: ```js let sortedRows = Array.from(table.tBodies[0].rows) // 1 @@ -7,12 +7,12 @@ let sortedRows = Array.from(table.tBodies[0].rows) // 1 table.tBodies[0].append(...sortedRows); // (3) ``` -The step-by-step algorthm: +O algoritmo passo a passo: -1. Get all ``, from ``. -2. Then sort them comparing by the content of the first `` (the name field). -3. Now insert nodes in the right order by `.append(...sortedRows)`. +1. Obtenha todos os ``, de dentro do ``. +2. Depois ordene-os comparando pelo conteúdo do primeiro `` (o campo do nome). +3. Agora insira os nós na ordem correta com `.append(...sortedRows)`. -We don't have to remove row elements, just "re-insert", they leave the old place automatically. +Não precisamos remover os elementos de linha, apenas "reinseri-los", eles saem do lugar antigo automaticamente. -P.S. In our case, there's an explicit `` in the table, but even if HTML table doesn't have ``, the DOM structure always has it. +P.S. No nosso caso, há um `` explícito na tabela, mas mesmo que a tabela HTML não tenha ``, a estrutura do DOM sempre o terá. diff --git a/2-ui/1-document/07-modifying-document/12-sort-table/solution.view/index.html b/2-ui/1-document/07-modifying-document/12-sort-table/solution.view/index.html index 40692031a..db5f9d8e9 100644 --- a/2-ui/1-document/07-modifying-document/12-sort-table/solution.view/index.html +++ b/2-ui/1-document/07-modifying-document/12-sort-table/solution.view/index.html @@ -3,7 +3,7 @@ - + diff --git a/2-ui/1-document/07-modifying-document/12-sort-table/source.view/index.html b/2-ui/1-document/07-modifying-document/12-sort-table/source.view/index.html index 9071c88ee..22e949865 100644 --- a/2-ui/1-document/07-modifying-document/12-sort-table/source.view/index.html +++ b/2-ui/1-document/07-modifying-document/12-sort-table/source.view/index.html @@ -3,7 +3,7 @@
      NameSurnameAgeNomeSobrenomeIdade
      - + @@ -23,5 +23,5 @@
      NameSurnameAgeNomeSobrenomeIdade
      diff --git a/2-ui/1-document/07-modifying-document/12-sort-table/task.md b/2-ui/1-document/07-modifying-document/12-sort-table/task.md index 7cdba35bc..f7213705a 100644 --- a/2-ui/1-document/07-modifying-document/12-sort-table/task.md +++ b/2-ui/1-document/07-modifying-document/12-sort-table/task.md @@ -2,15 +2,15 @@ importance: 5 --- -# Sort the table +# Ordene a tabela -There's a table: +Há uma tabela: ```html run - + @@ -30,6 +30,6 @@ There's a table:
      NameSurnameAgeNomeSobrenomeIdade
      ``` -There may be more rows in it. +Pode haver mais linhas nela. -Write the code to sort it by the `"name"` column. +Escreva o código para ordená-la pela coluna `"nome"`. diff --git a/2-ui/1-document/07-modifying-document/4-clear-elem/solution.md b/2-ui/1-document/07-modifying-document/4-clear-elem/solution.md index 62c3386d8..6c7bd4d4d 100644 --- a/2-ui/1-document/07-modifying-document/4-clear-elem/solution.md +++ b/2-ui/1-document/07-modifying-document/4-clear-elem/solution.md @@ -1,5 +1,5 @@ -First, let's see how *not* to do it: +Primeiro, vamos ver como *não* fazer isso: ```js function clear(elem) { @@ -9,11 +9,11 @@ function clear(elem) { } ``` -That won't work, because the call to `remove()` shifts the collection `elem.childNodes`, so elements start from the index `0` every time. But `i` increases, and some elements will be skipped. +Isso não vai funcionar, porque a chamada a `remove()` desloca a coleção `elem.childNodes`, então os elementos começam a partir do índice `0` a cada vez. Mas `i` aumenta, e alguns elementos serão pulados. -The `for..of` loop also does the same. +O loop `for..of` também faz a mesma coisa. -The right variant could be: +A variante correta poderia ser: ```js function clear(elem) { @@ -23,7 +23,7 @@ function clear(elem) { } ``` -And also there's a simpler way to do the same: +E também há um jeito mais simples de fazer a mesma coisa: ```js function clear(elem) { diff --git a/2-ui/1-document/07-modifying-document/4-clear-elem/task.md b/2-ui/1-document/07-modifying-document/4-clear-elem/task.md index 938d53470..dca6e3b05 100644 --- a/2-ui/1-document/07-modifying-document/4-clear-elem/task.md +++ b/2-ui/1-document/07-modifying-document/4-clear-elem/task.md @@ -2,19 +2,19 @@ importance: 5 --- -# Clear the element +# Limpe o elemento -Create a function `clear(elem)` that removes everything from the element. +Crie uma função `clear(elem)` que remove tudo do elemento. ```html run height=60
        -
      1. Hello
      2. -
      3. World
      4. +
      5. Olá
      6. +
      7. Mundo
      ``` diff --git a/2-ui/1-document/07-modifying-document/5-why-aaa/solution.md b/2-ui/1-document/07-modifying-document/5-why-aaa/solution.md index 3d1f6698f..9bf134e93 100644 --- a/2-ui/1-document/07-modifying-document/5-why-aaa/solution.md +++ b/2-ui/1-document/07-modifying-document/5-why-aaa/solution.md @@ -1,9 +1,9 @@ -The HTML in the task is incorrect. That's the reason of the odd thing. +O HTML na tarefa está incorreto. Essa é a razão da coisa estranha. -The browser has to fix it automatically. But there may be no text inside the ``: according to the spec only table-specific tags are allowed. So the browser shows `"aaa"` *before* the `
      `. +O navegador precisa corrigi-lo automaticamente. Mas não pode haver texto dentro de `
      `: de acordo com a especificação, só são permitidas tags específicas de tabela. Então o navegador mostra `"aaa"` *antes* da `
      `. -Now it's obvious that when we remove the table, it remains. +Agora é óbvio que, quando removemos a tabela, ele permanece. -The question can be easily answered by exploring the DOM using the browser tools. You'll see `"aaa"` before the `
      `. +A pergunta pode ser facilmente respondida explorando o DOM usando as ferramentas do navegador. Você vai ver `"aaa"` antes da `
      `. -The HTML standard specifies in detail how to process bad HTML, and such behavior of the browser is correct. +O padrão HTML especifica em detalhes como processar HTML incorreto, e esse comportamento do navegador está correto. diff --git a/2-ui/1-document/07-modifying-document/5-why-aaa/task.md b/2-ui/1-document/07-modifying-document/5-why-aaa/task.md index 861f70503..dfd7f16bf 100644 --- a/2-ui/1-document/07-modifying-document/5-why-aaa/task.md +++ b/2-ui/1-document/07-modifying-document/5-why-aaa/task.md @@ -2,26 +2,26 @@ importance: 1 --- -# Why does "aaa" remain? +# Por que "aaa" permanece? -In the example below, the call `table.remove()` removes the table from the document. +No exemplo abaixo, a chamada `table.remove()` remove a tabela do documento. -But if you run it, you can see that the text `"aaa"` is still visible. +Mas se você executar, pode ver que o texto `"aaa"` ainda fica visível. -Why does that happen? +Por que isso acontece? ```html height=100 run
      aaa - +
      TestTeste
      ``` diff --git a/2-ui/1-document/07-modifying-document/6-create-list/solution.md b/2-ui/1-document/07-modifying-document/6-create-list/solution.md index 1669be18f..39ad5da6f 100644 --- a/2-ui/1-document/07-modifying-document/6-create-list/solution.md +++ b/2-ui/1-document/07-modifying-document/6-create-list/solution.md @@ -1 +1 @@ -Please note the usage of `textContent` to assign the `
    • ` content. +Note o uso de `textContent` para atribuir o conteúdo do `
    • `. diff --git a/2-ui/1-document/07-modifying-document/6-create-list/solution.view/index.html b/2-ui/1-document/07-modifying-document/6-create-list/solution.view/index.html index 071645e8d..40363ab80 100755 --- a/2-ui/1-document/07-modifying-document/6-create-list/solution.view/index.html +++ b/2-ui/1-document/07-modifying-document/6-create-list/solution.view/index.html @@ -1,14 +1,14 @@ -

      Create a list

      +

      Crie uma lista

      ``` -Please note, at the last line `(*)` we append `DocumentFragment`, but it "blends in", so the resulting structure will be: +Note que, na última linha `(*)`, anexamos um `DocumentFragment`, mas ele "se funde", então a estrutura resultante será: ```html
        @@ -368,7 +368,7 @@ Please note, at the last line `(*)` we append `DocumentFragment`, but it "blends
      ``` -`DocumentFragment` is rarely used explicitly. Why append to a special kind of node, if we can return an array of nodes instead? Rewritten example: +`DocumentFragment` raramente é usado explicitamente. Por que anexar a um tipo especial de nó, se podemos retornar um array de nós em vez disso? Exemplo reescrito: ```html run
        @@ -387,27 +387,27 @@ function getListContent() { } *!* -ul.append(...getListContent()); // append + "..." operator = friends! +ul.append(...getListContent()); // append + operador "..." = amigos! */!* ``` -We mention `DocumentFragment` mainly because there are some concepts on top of it, like [template](info:template-element) element, that we'll cover much later. +Mencionamos `DocumentFragment` principalmente porque existem alguns conceitos construídos sobre ele, como o elemento [template](info:template-element), que vamos abordar bem mais adiante. -## Old-school insert/remove methods +## Métodos antigos de inserir/remover [old] -There are also "old school" DOM manipulation methods, existing for historical reasons. +Também existem métodos "antiquados" de manipulação do DOM, que existem por razões históricas. -These methods come from really ancient times. Nowadays, there's no reason to use them, as modern methods, such as `append`, `prepend`, `before`, `after`, `remove`, `replaceWith`, are more flexible. +Esses métodos vêm de tempos realmente antigos. Hoje em dia, não há motivo para usá-los, já que métodos modernos, como `append`, `prepend`, `before`, `after`, `remove`, `replaceWith`, são mais flexíveis. -The only reason we list these methods here is that you can find them in many old scripts: +A única razão pela qual listamos esses métodos aqui é que você pode encontrá-los em muitos scripts antigos: `parentElem.appendChild(node)` -: Appends `node` as the last child of `parentElem`. +: Anexa `node` como o último filho de `parentElem`. - The following example adds a new `
      • ` to the end of `
          `: + O exemplo a seguir adiciona um novo `
        1. ` ao final de `
            `: ```html run height=100
              @@ -418,16 +418,16 @@ The only reason we list these methods here is that you can find them in many old ``` `parentElem.insertBefore(node, nextSibling)` -: Inserts `node` before `nextSibling` into `parentElem`. +: Insere `node` antes de `nextSibling` em `parentElem`. - The following code inserts a new list item before the second `
            1. `: + O código a seguir insere um novo item de lista antes do segundo `
            2. `: ```html run height=100
                @@ -437,26 +437,26 @@ The only reason we list these methods here is that you can find them in many old
              ``` - To insert `newLi` as the first element, we can do it like this: + Para inserir `newLi` como o primeiro elemento, podemos fazer assim: ```js list.insertBefore(newLi, list.firstChild); ``` `parentElem.replaceChild(node, oldChild)` -: Replaces `oldChild` with `node` among children of `parentElem`. +: Substitui `oldChild` por `node` entre os filhos de `parentElem`. `parentElem.removeChild(node)` -: Removes `node` from `parentElem` (assuming `node` is its child). +: Remove `node` de `parentElem` (assumindo que `node` é um de seus filhos). - The following example removes first `
            3. ` from `
                `: + O exemplo a seguir remove o primeiro `
              1. ` de `
                  `: ```html run height=100
                    @@ -471,91 +471,91 @@ The only reason we list these methods here is that you can find them in many old ``` -All these methods return the inserted/removed node. In other words, `parentElem.appendChild(node)` returns `node`. But usually the returned value is not used, we just run the method. +Todos esses métodos retornam o nó inserido/removido. Em outras palavras, `parentElem.appendChild(node)` retorna `node`. Mas geralmente o valor retornado não é usado, apenas executamos o método. -## A word about "document.write" +## Uma palavra sobre "document.write" -There's one more, very ancient method of adding something to a web-page: `document.write`. +Há mais um método bem antigo de adicionar algo a uma página web: `document.write`. -The syntax: +A sintaxe: ```html run -

                    Somewhere in the page...

                    +

                    Em algum lugar na página...

                    *!* */!* -

                    The end

                    +

                    O fim

                    ``` -The call to `document.write(html)` writes the `html` into page "right here and now". The `html` string can be dynamically generated, so it's kind of flexible. We can use JavaScript to create a full-fledged webpage and write it. +A chamada a `document.write(html)` escreve o `html` na página "aqui e agora mesmo". A string `html` pode ser gerada dinamicamente, então é relativamente flexível. Podemos usar JavaScript para criar uma página web completa e escrevê-la. -The method comes from times when there was no DOM, no standards... Really old times. It still lives, because there are scripts using it. +O método vem de tempos em que não havia DOM, nem padrões... Tempos realmente antigos. Ele ainda existe, porque há scripts que o usam. -In modern scripts we can rarely see it, because of the following important limitation: +Em scripts modernos, raramente o vemos, por causa da seguinte limitação importante: -**The call to `document.write` only works while the page is loading.** +**A chamada a `document.write` só funciona enquanto a página está carregando.** -If we call it afterwards, the existing document content is erased. +Se a chamarmos depois, o conteúdo existente do documento é apagado. -For instance: +Por exemplo: ```html run -

                    After one second the contents of this page will be replaced...

                    +

                    Depois de um segundo o conteúdo desta página será substituído...

                    *!* */!* ``` -So it's kind of unusable at "after loaded" stage, unlike other DOM methods we covered above. +Então ele é praticamente inutilizável na fase "depois de carregado", diferente dos outros métodos do DOM que vimos acima. -That's the downside. +Essa é a desvantagem. -There's an upside also. Technically, when `document.write` is called while the browser is reading ("parsing") incoming HTML, and it writes something, the browser consumes it just as if it were initially there, in the HTML text. +Também há uma vantagem. Tecnicamente, quando `document.write` é chamado enquanto o navegador está lendo ("analisando") o HTML que chega, e ele escreve algo, o navegador o consome como se estivesse originalmente ali, no texto HTML. -So it works blazingly fast, because there's *no DOM modification* involved. It writes directly into the page text, while the DOM is not yet built. +Então funciona extremamente rápido, porque não há *nenhuma modificação do DOM* envolvida. Ele escreve diretamente no texto da página, enquanto o DOM ainda não foi construído. -So if we need to add a lot of text into HTML dynamically, and we're at page loading phase, and the speed matters, it may help. But in practice these requirements rarely come together. And usually we can see this method in scripts just because they are old. +Então, se precisarmos adicionar muito texto ao HTML dinamicamente, e estivermos na fase de carregamento da página, e a velocidade importar, isso pode ajudar. Mas, na prática, esses requisitos raramente se juntam. E geralmente vemos esse método em scripts só porque eles são antigos. -## Summary +## Resumo -- Methods to create new nodes: - - `document.createElement(tag)` -- creates an element with the given tag, - - `document.createTextNode(value)` -- creates a text node (rarely used), - - `elem.cloneNode(deep)` -- clones the element, if `deep==true` then with all descendants. +- Métodos para criar novos nós: + - `document.createElement(tag)` -- cria um elemento com a tag dada, + - `document.createTextNode(value)` -- cria um nó de texto (raramente usado), + - `elem.cloneNode(deep)` -- clona o elemento, se `deep==true` então com todos os descendentes. -- Insertion and removal: - - `node.append(...nodes or strings)` -- insert into `node`, at the end, - - `node.prepend(...nodes or strings)` -- insert into `node`, at the beginning, - - `node.before(...nodes or strings)` –- insert right before `node`, - - `node.after(...nodes or strings)` –- insert right after `node`, - - `node.replaceWith(...nodes or strings)` –- replace `node`. - - `node.remove()` –- remove the `node`. +- Inserção e remoção: + - `node.append(...nós ou strings)` -- insere em `node`, no final, + - `node.prepend(...nós ou strings)` -- insere em `node`, no início, + - `node.before(...nós ou strings)` –- insere logo antes de `node`, + - `node.after(...nós ou strings)` –- insere logo depois de `node`, + - `node.replaceWith(...nós ou strings)` –- substitui `node`. + - `node.remove()` –- remove o `node`. - Text strings are inserted "as text". + Strings de texto são inseridas "como texto". -- There are also "old school" methods: +- Também existem métodos "antiquados": - `parent.appendChild(node)` - `parent.insertBefore(node, nextSibling)` - `parent.removeChild(node)` - `parent.replaceChild(newElem, node)` - All these methods return `node`. + Todos esses métodos retornam `node`. -- Given some HTML in `html`, `elem.insertAdjacentHTML(where, html)` inserts it depending on the value of `where`: - - `"beforebegin"` -- insert `html` right before `elem`, - - `"afterbegin"` -- insert `html` into `elem`, at the beginning, - - `"beforeend"` -- insert `html` into `elem`, at the end, - - `"afterend"` -- insert `html` right after `elem`. +- Dado algum HTML em `html`, `elem.insertAdjacentHTML(where, html)` o insere dependendo do valor de `where`: + - `"beforebegin"` -- insere `html` logo antes de `elem`, + - `"afterbegin"` -- insere `html` dentro de `elem`, no início, + - `"beforeend"` -- insere `html` dentro de `elem`, no final, + - `"afterend"` -- insere `html` logo depois de `elem`. - Also there are similar methods, `elem.insertAdjacentText` and `elem.insertAdjacentElement`, that insert text strings and elements, but they are rarely used. + Também existem métodos semelhantes, `elem.insertAdjacentText` e `elem.insertAdjacentElement`, que inserem strings de texto e elementos, mas são raramente usados. -- To append HTML to the page before it has finished loading: +- Para anexar HTML à página antes que ela termine de carregar: - `document.write(html)` - After the page is loaded such a call erases the document. Mostly seen in old scripts. + Depois que a página é carregada, essa chamada apaga o documento. Visto principalmente em scripts antigos. From 5e3edeb2c25c3df2b6ee19a1af586be92154d052 Mon Sep 17 00:00:00 2001 From: Diogo Marciano Date: Sat, 21 Nov 2026 23:16:47 -0300 Subject: [PATCH 2/2] Apply review suggestions from gabifs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix missing accent: "SAB" -> "SÁB" for Saturday's abbreviation - Translate "nested" as "aninhado/aninhados" instead of "encadeado", which in PT-BR programming usage means "chained" (method chaining, optional chaining), not "nested inside" - Align a comment showing expected output ("Árvores") with the singular data key ("Árvore") it refers to - Use the actual variable name `timerId` consistently instead of the incorrect `timerID` in prose and comments Co-Authored-By: Claude Sonnet 5 --- .../07-modifying-document/10-clock-setinterval/solution.md | 2 +- .../10-clock-setinterval/solution.view/index.html | 4 ++-- .../7-create-object-tree/source.view/index.html | 2 +- .../07-modifying-document/7-create-object-tree/task.md | 2 +- 2-ui/1-document/07-modifying-document/8-tree-count/task.md | 2 +- .../9-calendar-table/solution.view/index.html | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md index 436264909..4d68c8e24 100644 --- a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md +++ b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.md @@ -54,4 +54,4 @@ function clockStop() { Note que a chamada a `update()` não é apenas agendada em `clockStart()`, mas também executada imediatamente na linha `(*)`. Caso contrário, o visitante teria que esperar até a primeira execução do `setInterval`. E o relógio ficaria vazio até então. -Também é importante definir um novo intervalo em `clockStart()` apenas quando o relógio não estiver em execução. Caso contrário, clicar no botão de início várias vezes definiria múltiplos intervalos simultâneos. Pior ainda - manteríamos apenas o `timerID` do último intervalo, perdendo as referências a todos os outros. Então nunca mais conseguiríamos parar o relógio! Note que precisamos limpar o `timerID` quando o relógio é parado na linha `(**)`, para que ele possa ser iniciado novamente ao executar `clockStart()`. +Também é importante definir um novo intervalo em `clockStart()` apenas quando o relógio não estiver em execução. Caso contrário, clicar no botão de início várias vezes definiria múltiplos intervalos simultâneos. Pior ainda - manteríamos apenas o `timerId` do último intervalo, perdendo as referências a todos os outros. Então nunca mais conseguiríamos parar o relógio! Note que precisamos limpar o `timerId` quando o relógio é parado na linha `(**)`, para que ele possa ser iniciado novamente ao executar `clockStart()`. diff --git a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html index ae9a2bf78..de626b177 100644 --- a/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html +++ b/2-ui/1-document/07-modifying-document/10-clock-setinterval/solution.view/index.html @@ -44,7 +44,7 @@ function clockStart() { // define um novo intervalo apenas se o relógio estiver parado - // caso contrário, reescreveríamos a referência timerID do intervalo em execução e nunca mais conseguiríamos parar o relógio + // caso contrário, reescreveríamos a referência timerId do intervalo em execução e nunca mais conseguiríamos parar o relógio if (!timerId) { timerId = setInterval(update, 1000); } @@ -53,7 +53,7 @@ function clockStop() { clearInterval(timerId); - timerId = null; // <-- limpa o timerID para indicar que o relógio foi parado, para que seja possível iniciá-lo novamente em clockStart() + timerId = null; // <-- limpa o timerId para indicar que o relógio foi parado, para que seja possível iniciá-lo novamente em clockStart() } diff --git a/2-ui/1-document/07-modifying-document/7-create-object-tree/source.view/index.html b/2-ui/1-document/07-modifying-document/7-create-object-tree/source.view/index.html index 2e8b2c9af..aaea0c8da 100755 --- a/2-ui/1-document/07-modifying-document/7-create-object-tree/source.view/index.html +++ b/2-ui/1-document/07-modifying-document/7-create-object-tree/source.view/index.html @@ -18,7 +18,7 @@
                  1. salmão
    • -
    • Árvores +
    • Árvore
      • Enorme
          diff --git a/2-ui/1-document/07-modifying-document/7-create-object-tree/task.md b/2-ui/1-document/07-modifying-document/7-create-object-tree/task.md index f4897a215..dd4dcd391 100644 --- a/2-ui/1-document/07-modifying-document/7-create-object-tree/task.md +++ b/2-ui/1-document/07-modifying-document/7-create-object-tree/task.md @@ -4,7 +4,7 @@ importance: 5 # Crie uma árvore a partir do objeto -Escreva uma função `createTree` que cria uma lista `ul/li` encadeada a partir do objeto encadeado. +Escreva uma função `createTree` que cria uma lista `ul/li` aninhada a partir do objeto aninhado. Por exemplo: diff --git a/2-ui/1-document/07-modifying-document/8-tree-count/task.md b/2-ui/1-document/07-modifying-document/8-tree-count/task.md index c77900cf3..8f1bbeee1 100644 --- a/2-ui/1-document/07-modifying-document/8-tree-count/task.md +++ b/2-ui/1-document/07-modifying-document/8-tree-count/task.md @@ -4,7 +4,7 @@ importance: 5 # Mostrar descendentes em uma árvore -Há uma árvore organizada como `ul/li` encadeados. +Há uma árvore organizada como `ul/li` aninhados. Escreva o código que adiciona a cada `
        • ` o número de seus descendentes. Pule as folhas (nós sem filhos). diff --git a/2-ui/1-document/07-modifying-document/9-calendar-table/solution.view/index.html b/2-ui/1-document/07-modifying-document/9-calendar-table/solution.view/index.html index efccaac31..0b3bdf60f 100644 --- a/2-ui/1-document/07-modifying-document/9-calendar-table/solution.view/index.html +++ b/2-ui/1-document/07-modifying-document/9-calendar-table/solution.view/index.html @@ -32,7 +32,7 @@ let mon = month - 1; // meses em JS vão de 0..11, não de 1..12 let d = new Date(year, mon); - let table = ''; + let table = '
          SEGTERQUAQUISEXSABDOM
          '; // espaços para a primeira linha // de segunda-feira até o primeiro dia do mês
          SEGTERQUAQUISEXSÁBDOM