Please no jQuery code, as I want to learn javascript first and foremost.
I am just trying something out and I have a button in my html page that dynamically adds li items to a ul. Something to this effect:
HTML:
<ul id="myList">
</ul>
<input id="myButton" value="Click Me" type="submit" onclick="addItem();"></input>
And the JS for 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)
//is it a sunday -- only add sundays...
{
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]); //set the id attribute
var month = today.getMonth();
var day = today.getDate();
var year = today.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
l.appendChild(li); //add the li to the ul
}
today.setDate(today.getDate() + 1) //increment the day
count++;
}
}
This is nice however, next to each line item I would like to also add a hyperlink that would say ‘Remove’ so that if a user clicks on it, it then would remove that single li. Do I just do a document.createElement('a') ? and set its attribute via .setAttribute. But then how do I trigger the delete for that specific li? Here’s my try at it:
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;
if (!e) var e = window.event;
if (e.target) liNode = e.target;
else if (e.srcElement) liNode = e.srcElement;
if (liNode.nodeType == 3)
{ // defeat Safari bug
liNode = liNode.parentNode;
}
// l refers to ul which you've an instance of already
l.removeChild(liNode);
}
li.appendChild(a);
}
today.setDate(today.getDate() + 1)
count++;
}
}
But when I click the href link it does not remove anything…
Yes you can add
ausingvar anchor = document.createElement('a');. And yes, you can add attribute by usingsetAttributeor just by usinganchor.href = 'http://yourpath.com';. Then you can add event listener using following code: