Skip to content

Modifying document #281

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
Answer: **1 and 3**.
Risposta: **1 e 3**.

Both commands result in adding the `text` "as text" into the `elem`.

Here's an example:
Entrambi i commandi risultano nell'aggiunta di `text` "come testo" dentro a `elem`.
Ecco un esempio:

```html run height=80
<div id="elem1"></div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ importance: 5

# createTextNode vs innerHTML vs textContent

We have an empty DOM element `elem` and a string `text`.
Abbiamo `elem`, un elemento DOM vuoto, e una stringa`text`.

Which of these 3 commands will do exactly the same?
Quali di questi 3 comandi fanno esattamente la stessa cosa?

1. `elem.append(document.createTextNode(text))`
2. `elem.innerHTML = text`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Nota che la chiamata a `update()` non è programmata solo in `clockStart()`, ma immediatamente dopo l'esecuzione della linea `(*)`. Altrimenti il visitatore dovrebbe aspettare fino alla prima esecuzione di `setInterval`. E l'orologio sarebbe vuoto fino ad allora.

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()`.
E' altresì importante impostare il nuovo intervallo in `clockStart()` solo quando l'orologio non sta andando. Altrimenti cliccare il bottone start svariate volte imposterebbe multipli intervali concorrenti. Ancora peggio: terremmo solo il `timerID` dell'ultimo intervallo, perdendo la referenza a tutti gli altri. Così non potremmo più fermare l'orologio! Nota che dobbiamo rimuovere il `timerID` quando l'orologio viene fermato alla linea `(**)`, in modo da permettergi di ricominciare eseguendo `clockStart()`.
Original file line number Diff line number Diff line change
Expand Up @@ -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
// imposta un nuovo intervallo solo se l'orologio è fermo
// altrimenti dovremmo riscrivere la referenza di timerID all'intervallo in esecuzione e non potremmo più fermare l'orologio
if (!timerId) {
timerId = setInterval(update, 1000);
}
update(); // <-- start right now, don't wait 1 second till the first setInterval works
update(); // <-- comincia subito, non aspettare un secondo affinché il primo setInterval funzioni
}

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; // <-- rimuovi timerID per indicare che l'orologio è stato fermato, in modo da poterlo far ripartire in clockStart()
}

clockStart();
</script>

<!-- click on this button calls clockStart() -->
<!-- cliccare questo bottone chiama clockStart() -->
<input type="button" onclick="clockStart()" value="Start">

<!-- click on this button calls clockStop() -->
<!-- cliccare questo bottone chiama clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
<html>
<body>

<!-- click on this button calls clockStart() -->
<!-- cliccare questo bottone chiama clockStart() -->
<input type="button" onclick="clockStart()" value="Start">

<!-- click on this button calls clockStop() -->
<!-- cliccare questo bottone chiama clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">

</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 4

---

# Colored clock with setInterval
# Orologio colorato con setInterval

Create a colored clock like here:
Crea un orologio colorato come quello dell'esempio:

[iframe src="solution" height=60]

Use HTML/CSS for the styling, JavaScript only updates time in elements.
Usa HTML/CSS per lo styling, JavaScript aggiorna solo il tempo negli elementi.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

When we need to insert a piece of HTML somewhere, `insertAdjacentHTML` is the best fit.
Quando abbiamo bisogno di inserire dell'HTML da qualche parte, `insertAdjacentHTML` è la scelta migliore

The solution:
La soluzione:

```js
one.insertAdjacentHTML('afterend', '<li>2</li><li>3</li>');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Insert the HTML in the list
# Inserisci l'HTML nella lista

Write the code to insert `<li>2</li><li>3</li>` between two `<li>` here:
Scrivi il codice per inserire `<li>2</li><li>3</li>` tra i due `<li>` sotto:

```html
<ul id="ul">
Expand Down
14 changes: 7 additions & 7 deletions 2-ui/1-document/07-modifying-document/12-sort-table/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The solution is short, yet may look a bit tricky, so here I provide it with extensive comments:
La soluzione è breve, ma potrebbe sembrare difficile, quindi la commenteremo in dettaglio:

```js
let sortedRows = Array.from(table.tBodies[0].rows) // 1
Expand All @@ -7,12 +7,12 @@ let sortedRows = Array.from(table.tBodies[0].rows) // 1
table.tBodies[0].append(...sortedRows); // (3)
```

The step-by-step algorthm:
L'algoritmo passo per passo:

1. Get all `<tr>`, from `<tbody>`.
2. Then sort them comparing by the content of the first `<td>` (the name field).
3. Now insert nodes in the right order by `.append(...sortedRows)`.
1. Trova tutti i `<tr>` dentro `<tbody>`.
2. Ordinali comparando il contenuto del primo `<td>` (il campo con il nome).
3. Ora inserisci i nodi nel giusto ordine con `.append(...sortedRows)`.

We don't have to remove row elements, just "re-insert", they leave the old place automatically.
Non dobbiamo rimuovere gli elementi della fila, solo "re-inserirli", lasciano automaticamente il vecchio posto.

P.S. In our case, there's an explicit `<tbody>` in the table, but even if HTML table doesn't have `<tbody>`, the DOM structure always has it.
P.S. Nel nostro caso c'è un esplicito `<tbody>` nella tabella; ma se anche non vi fosse, la struttura DOM lo include sempre e comunque.
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@
</table>

<script>
// ... your code ...
// ... il tuo codice ...
</script>
8 changes: 4 additions & 4 deletions 2-ui/1-document/07-modifying-document/12-sort-table/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Sort the table
# Ordina la tabella

There's a table:
Ecco una tabella:

```html run
<table>
Expand All @@ -30,6 +30,6 @@ There's a table:
</table>
```

There may be more rows in it.
Potrebbero esserci più file dentro.

Write the code to sort it by the `"name"` column.
Scrivi il codice per ordinarla in base alla colonna `"name"`.
10 changes: 5 additions & 5 deletions 2-ui/1-document/07-modifying-document/4-clear-elem/solution.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

First, let's see how *not* to do it:
Prima, vediamo come *non* farlo:

```js
function clear(elem) {
Expand All @@ -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.
Questo non funziona perché la chiamata a `remove()` muove la collezione `elem.childNodes`, quindi gli elementi partono ogni volta dall'indice `0`. Ma `i` aumenta, perciò alcuni elementi verranno saltati.

The `for..of` loop also does the same.
Il loop `for..of` fa lo stesso.

The right variant could be:
La corretta variante potrebbe essere:

```js
function clear(elem) {
Expand All @@ -23,7 +23,7 @@ function clear(elem) {
}
```

And also there's a simpler way to do the same:
C'è un modo più semplice per fare lo stesso:

```js
function clear(elem) {
Expand Down
8 changes: 4 additions & 4 deletions 2-ui/1-document/07-modifying-document/4-clear-elem/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Clear the element
# Ripulisci l'elemento

Create a function `clear(elem)` that removes everything from the element.
Crea una funzione `clear(elem)` che rimuova tutto da un elemento.

```html run height=60
<ol id="elem">
Expand All @@ -13,8 +13,8 @@ Create a function `clear(elem)` that removes everything from the element.
</ol>

<script>
function clear(elem) { /* your code */ }
function clear(elem) { /* il tuo codice */ }

clear(elem); // clears the list
clear(elem); // Ripulisce la lista
</script>
```
10 changes: 5 additions & 5 deletions 2-ui/1-document/07-modifying-document/5-why-aaa/solution.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
The HTML in the task is incorrect. That's the reason of the odd thing.
L'HTML nel task è incorretto. Questa è la ragione della stranezza.

The browser has to fix it automatically. But there may be no text inside the `<table>`: according to the spec only table-specific tags are allowed. So the browser shows `"aaa"` *before* the `<table>`.
Il browser deve sistemarlo automaticamente. Ma non vi può essere testo dentro a `<table>`: secondo la specifica, solo gli specifici tag per le tabelle sono permessi. Perciò il browser aggiunge `"aaa"` *prima* di `<table>`.

Now it's obvious that when we remove the table, it remains.
Ora è ovvio perché, rimuovendo la tabella, il testo rimane.

The question can be easily answered by exploring the DOM using the browser tools. You'll see `"aaa"` before the `<table>`.
La domanda può facilmente trovare risposta esplorando il DOM con gli strumenti del browser. Mostra `"aaa"` prima di `<table>`.

The HTML standard specifies in detail how to process bad HTML, and such behavior of the browser is correct.
Lo standard HTML specifica in dettaglio come processare cattivo HTML, e questo comportamento del browser è corretto.
12 changes: 6 additions & 6 deletions 2-ui/1-document/07-modifying-document/5-why-aaa/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 1

---

# Why does "aaa" remain?
# Perché rimane "aaa"?

In the example below, the call `table.remove()` removes the table from the document.
Nell'esempio sotto, la chiamata a `table.remove()` rimuove la tabella dal documento.

But if you run it, you can see that the text `"aaa"` is still visible.
Ma se eseguiamo il codice, potrai vedere che il testo `"aaa"` è ancora visibile.

Why does that happen?
Perché?

```html height=100 run
<table id="table">
Expand All @@ -19,9 +19,9 @@ Why does that happen?
</table>

<script>
alert(table); // the table, as it should be
alert(table); // la tabella, come dovrebbe essere

table.remove();
// why there's still aaa in the document?
// perché aaa è ancora nel documento?
</script>
```
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Please note the usage of `textContent` to assign the `<li>` content.
Nota l'utilizzo di `textContent` per assegnare il contenuto a `<li>`.
16 changes: 8 additions & 8 deletions 2-ui/1-document/07-modifying-document/6-create-list/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ importance: 4

---

# Create a list
# Crea una lista

Write an interface to create a list from user input.
Scrivi un'interfaccia per creare una lista dagli input dell'utente.

For every list item:
Per ogni elemento della lista:

1. Ask a user about its content using `prompt`.
2. Create the `<li>` with it and add it to `<ul>`.
3. Continue until the user cancels the input (by pressing `key:Esc` or via an empty entry).
1. Chiedi all'utente il contenuto utilizzando `prompt`.
2. Crea il `<li>` con il contenuto e aggiungilo a `<ul>`.
3. Continua fino a quando l'utente non interrompe l'input (premendo `key:Esc` o inserendo un contenuto vuoto)

All elements should be created dynamically.
Tutti gli elementi devono essere creati dinamicamente.

If a user types HTML-tags, they should be treated like a text.
Se l'utente inserisce tag HTML, questi devono essere trattati come testo.

[demo src="solution"]
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
}

function createTreeDom(obj) {
// if there's no children, then the call returns undefined
// and the <ul> won't be created
// se non ci sono figli, la chiamata ritorna undefined
// e <ul> non verrà creato
if (!Object.keys(obj).length) return;

let ul = document.createElement('ul');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
container.innerHTML = createTreeText(obj);
}

function createTreeText(obj) { // standalone recursive function
function createTreeText(obj) { // funzione ricorsiva
let li = '';
let ul;
for (let key in obj) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The easiest way to walk the object is to use recursion.
Il modo più semplice per percorrere l'oggetto è utilizzando la ricorsione.

1. [The solution with innerHTML](sandbox:innerhtml).
2. [The solution with DOM](sandbox:build-tree-dom).
1. [La soluzione con innerHTML](sandbox:innerhtml).
2. [La soluzione con DOM](sandbox:build-tree-dom).
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
};

function createTree(container, data) {
/* your code */
/* il tuo codice */
}

createTree(document.getElementById('tree'), data);
Expand Down
20 changes: 10 additions & 10 deletions 2-ui/1-document/07-modifying-document/7-create-object-tree/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Create a tree from the object
# Crea un albero da un oggetto

Write a function `createTree` that creates a nested `ul/li` list from the nested object.
Scrivi una funzione `createTree` che crea una lista `ul/li` annidata partendo dall'oggetto annidato.

For instance:
Ad esempio:

```js
let data = {
Expand All @@ -28,7 +28,7 @@ let data = {
};
```

The syntax:
La sintassi:

```js
let container = document.getElementById('container');
Expand All @@ -37,15 +37,15 @@ createTree(container, data); // creates the tree in the container
*/!*
```

The result (tree) should look like this:
Il risultato (l'albero) dovrebbe somigliare a questo:

[iframe border=1 src="build-tree-dom"]

Choose one of two ways of solving this task:
Scegli uno dei due metodi per risolvere la task:

1. Create the HTML for the tree and then assign to `container.innerHTML`.
2. Create tree nodes and append with DOM methods.
1. Crea l'HTML per l'albero e assegnala a `container.innerHTML`.
2. Crea i nodi dell'albero e appendili utilizzando i metodi del DOM.

Would be great if you could do both.
Sarebbe grandioso se riuscissi con entrambi.

P.S. The tree should not have "extra" elements like empty `<ul></ul>` for the leaves.
P.S. L'albero non dovrebbe avere elementi "extra" -ad esempio`<ul></ul>` vuoti- come foglie.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
To append text to each `<li>` we can alter the text node `data`.
Per appendere testo a ogni `<li>` possiamo modificare il nodo di testo `data`.
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@
let lis = document.getElementsByTagName('li');

for (let li of lis) {
// get the count of all <li> below this <li>
// il conto di tutti i <li> sotto l'attuale <li>
let descendantsCount = li.getElementsByTagName('li').length;
if (!descendantsCount) continue;

// add directly to the text node (append to the text)
// aggiungi direttamente al nodo di testo (appendi al testo)
li.firstChild.data += ' [' + descendantsCount + ']';
}
</script>
Expand Down
Loading