settingsAccountsettings
Menusettings

Q: List of Items Task in HTML with DOM and JavaScript

+3 votes

Write a JS function that read the text inside an input field and appends the specified text to a list inside an HTML page.

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

Sample HTML:

<h1>List of Items</h1>
<ul id="items"><li>First</li><li>Second</li></ul>
<input type="text" id="newItemText" />
<input type="button" value="Add" onclick="addItem()">
<script>
  function addItem() {
    // TODO: add new item to the list
  }
</script>

Examples:

list of items javascript task

asked in JavaScript category by user Jolie Ann

2 Answers

+2 votes

Here is my solution:
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>List of Items:</h1>
<ul id="items">
    <li>First</li>
    <li>Second</li>
</ul>
<input type="text" id="newItemText">
<input type="button" value="Add an Item" onclick="addItem()">

<script>
    function addItem() {
        let input = document.getElementById("newItemText");
        if (input.value.length === 0) {
            return;
        }
        let text = input.value;
        let newLi = document.createElement("li");
        newLi.textContent = text;
        document.getElementById("items").appendChild(newLi);
        input.value = "";
    }
</script>
</body>
</html>

 

answered by user matthew44
0 votes
<script>
function addItem() {
let text = document.getElementById("newItemText").value;
let li = document.createElement("li");
li.textContent = text;
let items = document.getElementById("items");
 
items.appendChild(li);
document.getElementById("newItemText").value = "";
}
</script>

 

answered by user mitko
...