3
07/11/2024 12:59 오후
주제 스타터
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>
예시:

1개 답글
2
07/11/2024 1:01 오후
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>
...and another one:
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>
