Update at the bottom of this answer to adapt to the comments
You don't really need an id
for each list item.
Also, depending on your li
's content, you might want to use textContent
in stead of innerHTML
to check the content. See innerText vs innerHtml vs label vs text vs textContent vs outerText for more information on that topic.
Fiddle (with comments): http://jsfiddle.net/c19u7074/3/
HTML
<ul id="lista">
</ul>
JavaScript
function addlist2(nombre, fecha) {
var node = document.createElement("li");
var textnode = document.createTextNode(nombre + " ");
var textnode2 = document.createTextNode(fecha);
node.appendChild(textnode);
node.appendChild(textnode2);
document.getElementById("lista").appendChild(node);
// Add a listener to the node
node.addEventListener("click", clickHandler);
}
function clickHandler(e) {
// Get node content as a string
var nodeText = e.target.textContent;
// Trim whitespaces from the string and check if they match any criteria you like
switch (nodeText.trim()) {
case "dog":
// It's a dog! So do dog stuff here
alert("woof woof");
break;
case "bird":
// It's a bird! So do bird stuff here
alert("tweet tweet");
break;
default:
// Else, do stuff below
}
}
addlist2("dog", "");
addlist2("bird", "");
Update
As you asked in the comments on this answer: opening a window with a fixed URL and variable part depending on the li
s contents is possible.
Updated Fiddle: http://jsfiddle.net/c19u7074/4/
Updated Javascript (only the clickHandler
function got updated)
function clickHandler(e) {
// Get node content as a string
var nodeText = e.target.textContent;
// Open a window pointing to a fixed URL with a variable part containing the clicked item's contents
// Trim whitespaces from the string and check if they match any criteria you like
window.open('https://www.google.be/?q=' + nodeText.trim())
}