0

I am making is a simple TO DO list which I uses the function appendChild to create an element when I click the button.

How do you create an ID for an element created with appendChild?

var input = document.getElementById("input-0");
//Create button to add LI

var AddGoal = document.getElementById('btn');
AddGoal.addEventListener('click', function (){
    var Ulist = document.getElementById('MyList');
    var NewLi = document.createElement('li');
    var text = document.getElementById('input-0').value;
    //var createtext = document.createTextNode(input.nodeValue);
    //NewLi.appendChild(t);
    Ulist.appendChild(NewLi);
    //document.body.appendChild(NewLi);
    NewLi.innerText = text;
});

var GetLiedto = document.getElementsByClassName('li');
GetLiedto.addEventListener ('mouseover', function (){
    GetLiedto.display.color = 'red';    
});

/*
var AddGoal = document.getElementById('btn');
AddGoal.addEventListener('click', function (){
    var Ulist = document.getElementById('MyList');
    var NewLi = document.createElement('li');
    var text = document.getElementById('input-0').value;
    //var createtext = document.createTextNode(input.nodeValue);
    //NewLi.appendChild(t);
    document.body.appendChild(NewLi);
    //document.body.appendChild(NewLi);
    NewLi.innerText = text;
});
*/
Clint
  • 2,696
  • 23
  • 42
  • Does this answer your question? [JavaScript Adding an ID attribute to another created Element](https://stackoverflow.com/questions/19625646/javascript-adding-an-id-attribute-to-another-created-element) – benbotto Feb 26 '20 at 18:14

1 Answers1

0

You can modify the attributes of a newly created element either before or after you append it to the body. Both will result in assigning an ID to the new <li> elem.

Before:

AddGoal.addEventListener('click', function (){
   var NewLi = document.createElement('li');
   NewLi.id = "some-id";
   document.body.appendChild(NewLi);
});

After:

AddGoal.addEventListener('click', function (){
   var NewLi = document.createElement('li');
   document.body.appendChild(NewLi);
   NewLi.id = "some-id";
});
WillD
  • 5,170
  • 6
  • 27
  • 56