i'm new with HTML & JS and i face the following Problem.
i have an input in html that creates me an li Element (in combination with JS) is it possible to give every new created li element an own id? For example to delete an specific element?
For Example
.. ..at this time it creats only
i think it can be done with an for loop but i have no idea how to use it in my case.
See my JS code below: `
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
li.appendChild(document.createTextNode(Input.value));
ul.appendChild(li);
Input.value = "";
`
Thanks a lot :-)
I tried to insert a for loop into my code but after that it doesn't add any Element.
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
for (var i = 0; i < li.length; i )
li[i].id = 'abc-' i;
li.appendChild(document.createTextNode(Input.value));
ul.appendChild(li);
Input.value = "";
CodePudding user response:
Your for
loop needs curly braces to work properly:
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
for (var i = 0; i < li.length; i ) {
abcElements[i].id = 'abc-' i;
li.appendChild(document.createTextNode(Inputfield.value));
ul.appendChild(li);
}
Inputfield.value = "";
}
Otherwise only the immediate line after the for
statement will run as part of the loop.
There also appeared to be a typo - you had Input
instead of Inputfield
? But I notice there are some other variables used here which are not defined, so I assume some extra code was omitted?
CodePudding user response:
You could count the number of elements inside the <ul>
and use that as id for the <li>
:
var AddButton = document.getElementById("AddButton");
AddButton.addEventListener("click", NewEntry);
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var ul = document.querySelector("ul");
var li = document.createElement("li");
li.id = ul.childElementCount;
li.appendChild(document.createTextNode(Inputfield.value));
ul.appendChild(li);
Inputfield.value = "";
console.log(li);
}
<input type="text" id="Inputfield" />
<button id="AddButton">Add</button>
<ul></ul>