This commit is contained in:
Ilya Kantor 2018-10-07 22:03:05 +03:00
parent 6f8bd3c0de
commit 30862423b0
4 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,19 @@
Let's make a loop over `<li>`:
```js
for (let li of document.querySelectorAll('li')) {
...
}
```
In the loop we need to get the text inside every `li`. We can read it directly from the first child node, that is the text node:
```js
for (let li of document.querySelectorAll('li')) {
let title = li.firstChild.data;
// title is the text in <li> before any other nodes
}
```
Then we can get the number of descendants `li.getElementsByTagName('li')`.

View file

@ -0,0 +1,57 @@
<!DOCTYPE HTML>
<html>
<body>
<ul>
<li>Animals
<ul>
<li>Mammals
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
</ul>
</li>
<li>Other
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<ul>
<li>Aquarium
<ul>
<li>Guppy</li>
<li>Angelfish</li>
</ul>
</li>
<li>Sea
<ul>
<li>Sea trout</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
for (let li of document.querySelectorAll('li')) {
// get the title from the text node
let title = li.firstChild.data;
title = title.trim(); // remove extra spaces from ends
// get the descendants count
let count = li.getElementsByTagName('li').length;
alert(title + ': ' + count);
}
</script>
</body>
</html>

View file

@ -0,0 +1,47 @@
<!DOCTYPE HTML>
<html>
<body>
<ul>
<li>Animals
<ul>
<li>Mammals
<ul>
<li>Cows</li>
<li>Donkeys</li>
<li>Dogs</li>
<li>Tigers</li>
</ul>
</li>
<li>Other
<ul>
<li>Snakes</li>
<li>Birds</li>
<li>Lizards</li>
</ul>
</li>
</ul>
</li>
<li>Fishes
<ul>
<li>Aquarium
<ul>
<li>Guppy</li>
<li>Angelfish</li>
</ul>
</li>
<li>Sea
<ul>
<li>Sea trout</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
// ... your code...
</script>
</body>
</html>

View file

@ -0,0 +1,14 @@
importance: 5
---
# Count descendants
There's a tree structured as nested `ul/li`.
Write the code that for each `<li>` shows:
1. What's the text inside it (without the subtree)
2. The number of nested `<li>` -- all descendants, including the deeply nested ones.
[demo src="solution"]