settingsAccountsettings
Menusettings

Q: Text from List (task with DOM and jQuery)

+3 votes

A HTML page holding a list of items and an [Extract Text] button is given. Implement the extractText function which will be called when the button's onClick event is fired.

HTML and JavaScript Code - You are given the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Text from List</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
    <script src="extractText.js"></script>
</head>
<body>
    <ul id="items">
        <li>first item</li>
        <li>second item</li>
        <li>third item</li>
    </ul>
    <button onclick="extractText()">
Extract Text</button>
    <div id="result"></div>
</body>
</html>

Examples:

text from list javascript jquery

asked in JavaScript category by user hues

1 Answer

+2 votes

The HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Text from List</title>
    <!--<script src="https://code.jquery.com/jquery-3.2.1.min.js"-->
            <!--integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>-->
    <script src="src/jquery-3.2.1.min.js"></script>
    <script src="src/extractText.js"></script>
</head>
<body>
<ul id="items">
    <li>first item</li>
    <li>second item</li>
    <li>third item</li>
</ul>
<button id="showItems" onclick="extractText()">
    Extract Text
</button>
<div id="result"></div>
</body>
</html>

The jQuery code:

function extractText() {
    let items = $("ul#items li")
        .toArray()
        .map(li => li.textContent)
        .join(", ");
    $("#result").text(items);
}
answered by user icabe
edited by user golearnweb
...