Skip to content

Modifying the document #186

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 1 commit into from
Apr 11, 2020
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,8 @@
Answer: **1 and 3**.
Réponse : **1 et 3**.

Both commands result in adding the `text` "as text" into the `elem`.
Les deux commandes ont pour résultat d'ajouter le `texte` "en tant que texte" dans `elem`.

Here's an example:
Voici un exemple :

```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`.
Nous avons un élément DOM vide `elem` et une chaîne de caractères `text`.

Which of these 3 commands do exactly the same?
Lesquelles de ces 3 commandes font exactement la même chose ?

1. `elem.append(document.createTextNode(text))`
2. `elem.innerHTML = text`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
First, let's make HTML/CSS.
Tout d'abord, créons notre HTML/CSS.

Each component of the time would look great in its own `<span>`:
Chaque composante du temps aurait fière allure dans son propre `<span>` :

```html
<div id="clock">
<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div>
```

Also we'll need CSS to color them.
Nous aurons également besoin de CSS pour les colorer.

The `update` function will refresh the clock, to be called by `setInterval` every second:
La fonction `update` rafraîchira l'horloge, qui sera appelée par `setInterval` toutes les secondes :

```js
function update() {
Expand All @@ -32,14 +32,14 @@ function update() {
}
```

In the line `(*)` we every time check the current date. The calls to `setInterval` are not reliable: they may happen with delays.
Dans la ligne `(*)` nous vérifions à chaque fois la date actuelle. Les appels à `setInterval` ne sont pas fiables : ils peuvent survenir avec des retards.

The clock-managing functions:
Les fonctions de gestion d'horloge :

```js
let timerId;

function clockStart() { // run the clock
function clockStart() { // exécute l'horloge
timerId = setInterval(update, 1000);
update(); // (*)
}
Expand All @@ -50,4 +50,4 @@ 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.
Veuillez noter que l'appel à `update()` est non seulement planifié dans `clockStart()`, mais s'exécute immédiatement dans la ligne `(*)`. Sinon, le visiteur devra attendre la première exécution de `setInterval`. Et l'horloge serait vide jusque-là.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ importance: 4

---

# Colored clock with setInterval
# Horloge colorée avec setInterval

Create a colored clock like here:
Créez une horloge colorée comme ici :

[iframe src="solution" height=60]

Use HTML/CSS for the styling, JavaScript only updates time in elements.
Utilisez HTML/CSS pour le style, JavaScript ne met à jour que le temps dans les éléments.
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.
Lorsque nous devons insérer un morceau de HTML quelque part, `insertAdjacentHTML` est le meilleur choix.

The solution:
La solution :

```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
# Insérez le HTML dans la liste

Write the code to insert `<li>2</li><li>3</li>` between two `<li>` here:
Écrivez le code pour insérer `<li>2</li><li>3</li>` entre deux `<li>` ici :

```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 solution est courte, mais peut sembler un peu délicate, alors ici je la présente avec de nombreux commentaires :

```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'algorithme pas à pas :

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. Obtenez tous les `<tr>` de `<tbody>`.
2. Triez-les ensuite en les comparant au contenu du premier `<td>` (le champ du nom).
3. Insérez maintenant les nœuds dans le bon ordre par `.append(...sortedRows)`.

We don't have to remove row elements, just "re-insert", they leave the old place automatically.
Nous n'avons pas à supprimer les éléments de ligne, il suffit de les "réinsérer", ils quittent automatiquement l'ancien emplacement.

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. Dans notre cas, il y a un `<tbody>` explicite dans le tableau, mais même si le tableau HTML n'a pas de `<tbody>`, la structure DOM l'a toujours.
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
# Trier le tableau

There's a table:
Il y a un tableau :

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

There may be more rows in it.
Il peut y avoir plus de lignes.

Write the code to sort it by the `"name"` column.
Écrivez le code pour le trier par la colonne `"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:
Voyons d'abord comment ne *pas* le faire :

```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.
Cela ne fonctionnera pas, car l'appel à `remove()` décale la collection `elem.childNodes`, donc les éléments commencent à partir de l'index `0` à chaque fois. Mais `i` augmente et certains éléments seront ignorés.

The `for..of` loop also does the same.
La boucle `for..of` fait de même.

The right variant could be:
La bonne variante pourrait être :

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

And also there's a simpler way to do the same:
Et il existe également un moyen plus simple de faire de même :

```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
# Effacer l'élément

Create a function `clear(elem)` that removes everything from the element.
Créez une fonction `clear(elem)` qui supprime tout de l'élément.

```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) { /* votre code */ }

clear(elem); // clears the list
clear(elem); // efface la liste
</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.
Le code HTML de cette tâche est incorrect. Voilà la raison de la chose étrange.

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 adds `"aaa"` *before* the `<table>`.
Le navigateur doit le réparer automatiquement. Mais il peut ne pas y avoir de texte à l'intérieur de la `<table>` : selon la spécification, seules les balises spécifiques à la table sont autorisées. Le navigateur ajoute donc `"aaa"` *avant* la `<table>`.

Now it's obvious that when we remove the table, it remains.
Maintenant, il est évident que lorsque nous retirons la `table`, la chaîne de caractères reste.

The question can be easily answered by exploring the DOM using the browser tools. It shows `"aaa"` before the `<table>`.
La question peut être facilement répondue en explorant le DOM à l'aide des outils du navigateur. Il montre `"aaa"` avant la `<table>`.

The HTML standard specifies in detail how to process bad HTML, and such behavior of the browser is correct.
Le standard HTML spécifie en détail comment traiter un mauvais HTML, et un tel comportement du navigateur est correct.
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?
# Pourquoi "aaa" reste-t-il ?

In the example below, the call `table.remove()` removes the table from the document.
Dans l'exemple ci-dessous, l'appel `table.remove()` supprime le tableau du document.

But if you run it, you can see that the text `"aaa"` is still visible.
mais si vous l'exécutez, vous pouvez voir que le texte `"aaa"` est toujours visible.

Why does that happen?
Pourquoi cela se produit-il ?

```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 table, comme il se doit

table.remove();
// why there's still aaa in the document?
// pourquoi y a-t-il encore aaa dans le document ?
</script>
```
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Please note the usage of `textContent` to assign the `<li>` content.
Veuillez noter l'utilisation de `textContent` pour attribuer le contenu `<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
# Créer une liste

Write an interface to create a list from user input.
Écrivez une interface pour créer une liste à partir des entrées utilisateur.

For every list item:
Pour chaque élément de la liste :

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 CANCEL in prompt).
1. Interrogez un utilisateur sur son contenu en utilisant `prompt`.
2. Créez le `<li>` avec et ajoutez-le à `<ul>`.
3. Continuez jusqu'à ce que l'utilisateur annule l'entrée (en appuyant sur la touche `key:Esc` ou CANCEL dans le prompt).

All elements should be created dynamically.
Tous les éléments doivent être créés dynamiquement.

If a user types HTML-tags, they should be treated like a text.
Si un utilisateur tape des balises HTML, elles doivent être traitées comme un texte.

[demo src="solution"]
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.
La façon la plus simple de parcourir l'objet est d'utiliser la récursivité.

1. [The solution with innerHTML](sandbox:innerhtml).
2. [The solution with DOM](sandbox:build-tree-dom).
1. [La solution avec innerHTML](https://plnkr.co/edit/PzjPAk9yKHeKkT36?p=preview).
2. [La solution avec DOM](https://plnkr.co/edit/e3TEVqQrm7ZqZkn6?p=preview).
22 changes: 11 additions & 11 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
# Créer un arbre à partir de l'objet

Write a function `createTree` that creates a nested `ul/li` list from the nested object.
Écrivez une fonction `createTree` qui crée une liste imbriquée `ul/li` à partir de l'objet imbriqué.

For instance:
Par exemple :

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

The syntax:
La syntaxe :

```js
let container = document.getElementById('container');
*!*
createTree(container, data); // creates the tree in the container
createTree(container, data); // crée l'arbre dans le conteneur
*/!*
```

The result (tree) should look like this:
Le résultat (arbre) devrait ressembler à ceci :

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

Choose one of two ways of solving this task:
Choisissez l'une des deux façons de résoudre cette tâche :

1. Create the HTML for the tree and then assign to `container.innerHTML`.
2. Create tree nodes and append with DOM methods.
1. Créez le code HTML de l'arborescence, puis attribuez-le à `container.innerHTML`.
2. Créez des nœuds d'arbre et ajoutez-les avec les méthodes DOM.

Would be great if you could do both.
Ce serait génial si vous pouviez faire les deux.

P.S. The tree should not have "extra" elements like empty `<ul></ul>` for the leaves.
P.S. L'arbre ne doit pas avoir d'éléments "supplémentaires" comme des `<ul></ul>` vides pour les feuilles (de l'arbre).
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`.
Pour ajouter du texte à chaque `<li>`, nous pouvons modifier le nœud texte `data`.
8 changes: 4 additions & 4 deletions 2-ui/1-document/07-modifying-document/8-tree-count/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ importance: 5

---

# Show descendants in a tree
# Afficher les descendants dans un arbre

There's a tree organized as nested `ul/li`.
Il y a un arbre organisé comme un `ul/li` imbriqué.

Write the code that adds to each `<li>` the number of its descendants. Skip leaves (nodes without children).
Écrivez le code qui ajoute à chaque `<li>` le nombre de ses descendants. Sautez les feuilles (nœuds sans enfants).

The result:
Le resultat :

[iframe border=1 src="solution"]
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
We'll create the table as a string: `"<table>...</table>"`, and then assign it to `innerHTML`.
Nous allons créer le tableau sous forme de chaîne de caractères : `"<table>...</table>"`, puis l'affecter à `innerHTML`.

The algorithm:
L'algorithme :

1. Create the table header with `<th>` and weekday names.
2. Create the date object `d = new Date(year, month-1)`. That's the first day of `month` (taking into account that months in JavaScript start from `0`, not `1`).
3. First few cells till the first day of the month `d.getDay()` may be empty. Let's fill them in with `<td></td>`.
4. Increase the day in `d`: `d.setDate(d.getDate()+1)`. If `d.getMonth()` is not yet the next month, then add the new cell `<td>` to the calendar. If that's a Sunday, then add a newline <code>"&lt;/tr&gt;&lt;tr&gt;"</code>.
5. If the month has finished, but the table row is not yet full, add empty `<td>` into it, to make it square.
1. Créer l'en-tête du tableau avec les noms `<th>` et les jours de la semaine.
2. Créez l'objet de date `d = new Date(year, month-1)`. C'est le premier jour de `month` (en tenant compte du fait que les mois en JavaScript commencent à `0`, pas à `1`).
3. Les premières cellules jusqu'au premier jour du mois `d.getDay()` peuvent être vides. Remplissons-les avec `<td></td>`.
4. Augmentez le jour en `d`: `d.setDate(d.getDate()+1)`. Si `d.getMonth()` n'est pas encore le mois suivant, alors ajoutez la nouvelle cellule `<td>` au calendrier. Si c'est un dimanche, ajoutez une nouvelle ligne <code>"&lt;/tr&gt;&lt;tr&gt;"</code>.
5. Si le mois est terminé, mais que la ligne du tableau n'est pas encore pleine, ajoutez-y un `<td>` vide pour le rendre carré.
12 changes: 6 additions & 6 deletions 2-ui/1-document/07-modifying-document/9-calendar-table/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ importance: 4

---

# Create a calendar
# Créer un calendrier

Write a function `createCalendar(elem, year, month)`.
Écrivez une fonction `createCalendar(elem, year, month)`.

The call should create a calendar for the given year/month and put it inside `elem`.
L'appel doit créer un calendrier pour l'année/le mois donné et le mettre dans `elem`.

The calendar should be a table, where a week is `<tr>`, and a day is `<td>`. The table top should be `<th>` with weekday names: the first day should be Monday, and so on till Sunday.
Le calendrier doit être un tableau, où une semaine est un `<tr>` et un jour est un `<td>`. Le dessus du tableau doit être un `<th>` avec les noms des jours de la semaine : le premier jour doit être le lundi, et ainsi de suite jusqu'au dimanche.

For instance, `createCalendar(cal, 2012, 9)` should generate in element `cal` the following calendar:
Par exemple, `createCalendar(cal, 2012, 9)` devrait générer dans l'élément `cal` le calendrier suivant :

[iframe height=210 src="solution"]

P.S. For this task it's enough to generate the calendar, should not yet be clickable.
P.S. Pour cette tâche, il suffit de générer le calendrier, il ne doit pas encore être cliquable.
Loading