So I have a start to a program where I generate a list of values in an unordered list with delete buttons that delete the corresponding entry into the list on each line. When I try to grab the id of the appropriate <li> element upon clicking the button, it will always return null and I’m not really sure why.
The list of values is generated with the following function when a button is clicked:
const random = () => { let remove = document.getElementById("generate"); remove.remove(); document.body.appendChild(list); while (chosenNames.length < 20) { let num = Math.floor(Math.random() * names.length) let inputName = names[num] if (chosenNames.indexOf(inputName) === -1) { chosenNames.push(inputName) }; }; const nameGen = (name) => { let add = document.createElement("li"); let deleteButton = document.createElement("button"); deleteButton.setAttribute("class", `deleteButton`); deleteButton.setAttribute("onclick", `deleteClick(${name})`); deleteButton.innerText = "X"; add.setAttribute("id", name); add.setAttribute("class", name); list.appendChild(add); add.innerHTML += `${name} `; add.appendChild(deleteButton); }; chosenNames.forEach(nameGen); };
This removes the first button and chooses 20 values to put into the list. Upon generation, the HTML ordered list looks like:
<ul id="nameList"> <li id="k" class="k"> k <button class="deleteButton" onclick="deleteClick(k)">X</button> </li> <li id="d" class="d"> d <button class="deleteButton" onclick="deleteClick(d)">X</button> </li> </ul>
Rinse and repeat for all 20 values. Based on this, I should be able to click the button and run the function deleteClick with the parameter of the letter it corresponds to. That function is as follows:
const deleteClick = (name) => { let getList = document.getElementById("nameList"); let element = document.getElementById(name); console.log(element); getList.removeChild(element); };
I haven’t fully worked out the removal part of it yet so I’m not sure if that’s wrong or not, but regardless, the output in the console is always null. So somehow this function isn’t grabbing the element with the correct id, and I’m not really sure why. Clicking on the button gives me the error
Uncaught TypeError: Failed to execute ‘removeChild’ on ‘Node’: parameter 1 is not of type ‘Node’.
which is not surprising, considering the parameter is null.
Any help or insight would be much appreciated 🙂
Advertisement
Answer
You need to output quotes around the name
value when setting the onclick
attributes, in order for the function call to receive a string value:
deleteButton.setAttribute("onclick", `deleteClick('${name}')`);