where am I getting wrong in this code? i want to add li to the ul element with the value entered by user in the input area. help me please!
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 class="bg-dark"> <div class="container bg-warning p-4"> <h1 class="text-center">LearnCodeOnline</h1> <div class="input-group"> <span class="input-group-text">todo</span> <textarea class="form-control" aria-label="With textarea"></textarea> </div> <button id="button" class="float-right">Add</button> <ul class="list-group"> <li class="list-group-item">An item</li> </ul> <!-- <button type="button" class="btn btn-success btn-lg mt-4 mx-auto d-block sort-btn" > Sort courses </button> --> </div> </body> </html>
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);
.appendChild("li")
, we'll give it an element and not string as it takes the element and not stringgetElementsByClassName()
returns an array so we will take the item at 0th index of the array in both the functions where it is there li = "task"
like this, we'll have to set its text by li.innerText = task
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.