[Risolto] Collect List Items Task in HTML with DOM and JavaScript

  

3
Argomento iniziale

Write a JS function that scans a given HTML list and appends all collected list items’ text to a text area on the same page when the user clicks on a button.

Input/Output:
There will be no input/output, your program should instead modify the DOM of the given HTML document.

Sample HTML:

<ul id="items">
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
</ul>
<textarea id="result"></textarea>
<br>
<button onclick="extractText()">Extract Text</button>
<script>
  function extractText() {
    // TODO
  }
</script>

Examples:

collect list items in javascript and html and dom

1 risposta
2

Here is the solution:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
 
<ul id="items">
    <li>first item</li>
    <li>second item</li>
    <li>third item</li>
</ul>
 
<textarea id="result"></textarea>
<br>
<button onclick="extractText()">Extract Text</button>
 
<script>
    function extractText() {
        let items = document.querySelectorAll("#items li");
        let result = document.getElementById("result");
        for (let li of items) {
            result.value += li.textContent + "\n";
        }
    }
</script>
</body>
</html>
Condividi: