I want to add li to the ul element with the value entered by user in the input area.
This is the error I am getting in console:
[Error] TypeError: document.getElementsByClassName("list-group").appendChild is not a function. (In 'document.getElementsByClassName("list-group").appendChild("li")', 'document.getElementsByClassName("list-group").appendChild' is undefined)
additem (script.js:7)
//this is my javascript code-->
function additem() {
var task = document.getElementsByClassName("input-group-text").value;
var li = document.createElement("li");
li.classList.add("list-group-item");
li = "task";
document.getElementsByClassName("list-group").appendChild("li");
}
document.getElementById("button").addEventListener("click",additem);
//<--!this is my html code-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LearnCodeOnline</title>
<link rel="stylesheet" href="./style.css" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
</head>
<body >
<div >
<h1 >LearnCodeOnline</h1>
<div >
<span >todo</span>
<textarea aria-label="With textarea"></textarea>
</div>
<button id="button" >Add</button>
<ul >
<li >An item</li>
</ul>
<!-- <button
type="button"
>
Sort courses
</button> -->
</div>
</body>
</html>
CodePudding user response:
JS:-
function additem() {
var task = document.getElementsByClassName("form-control")[0].value;
var li = document.createElement("li");
li.classList.add("list-group-item");
li.innerText = task;
document.getElementsByClassName("list-group")[0].appendChild(li);
}
document.getElementById("button").addEventListener("click",additem);
- Instead of doing
.appendChild("li"), we'll give it an element and not string as it takes the element and not string getElementsByClassName()returns an array so we will take the item at 0th index of the array in both the functions where it is there- also instead of setting
li = "task"like this, we'll have to set its text byli.innerText = task
