Please refrain from using jQuery code, as my main focus is on learning javascript.
I am currently experimenting with adding li
items dynamically to a ul
when a button on the HTML page is clicked. Here's a sample implementation:
HTML:
<ul id="myList">
</ul>
<input id="myButton" value="Click Me" type="submit" onclick="addItem();"/>
Here's the JavaScript function addItem()
:
function addItem()
{
var l = document.getElementById("myList");
var today = new Date();
var day2 = new Date();
day2.setDate(today.getDate() + 30);
var count = 1;
while(today.valueOf() < day2.valueOf())
{
if(today.getDay() == 0)
{
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]);
var month = today.getMonth();
var day = today.getDate();
var year = today.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
l.appendChild(li);
}
today.setDate(today.getDate() + 1)
count++;
}
}
Now, I would like to add a hyperlink next to each line item labeled 'Remove' so that users can click on it and delete the respective li
. To achieve this, I attempted to create an anchor element using document.createElement('a')
, but encountered issues triggering the deletion of the specific li
. Here's my attempt:
Edit
function addItem()
{
var l = document.getElementById("myList");
var today = new Date();
var day2 = new Date();
day2.setDate(today.getDate() + 30);
var count = 1;
while(today.valueOf() < day2.valueOf())
{
if(today.getDay() == 0)
{
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]);
var month = today.getMonth();
var day = today.getDate();
var year = today.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
l.appendChild(li);
var a = document.createElement('a');
a.setAttribute('href', '#');
a.innerHTML = "Remove";
a.onclick = function(e) {
var liNode = e.target.parentNode;
l.removeChild(liNode);
};
li.appendChild(a);
}
today.setDate(today.getDate() + 1)
count++;
}
}
Unfortunately, clicking the href link does not remove anything as expected...