DesAdams DesAdams - 1 year ago 79
HTML Question

Cannot add click events to list items

This is my first foray into using Javascript with HTML. I'm trying to add click events to the list items in an ordered list, but something about the way I'm doing it isn't working. Can somebody shed some light on this for me?

I create a function in my

that should delegate all click events on the list items of a specified list to a given function, and in that given function I try to raise a simple alert with the text of the list item. Eventually I want to do more, but I'm just trying to get the simple click events to work first.

<script type="text/javascript">
// Attach an event handler to the 'topfriends' list to handle click events.
function attachEventHandlerToList() {
document.getElementById("#top4list").delegate("li", "click", function(clickEvent) {


<div id="topfriends">
<h3>Top 4 Most Friendable Friends</h3>
<ol id="top4list" onload="attachEventHandlerToList()">

Answer Source

Let's do something like this

<ul id="parent-list">
    <li id="a">Item A</li>
    <li id="b">Item B</li>
    <li id="c">Item C</li>
    <li id="d">Item D</li>
    <li id="e">Item E</li>
    <li id="f">Item F</li>

Now write the javascript for this

<script type="text/javascript">
    // locate your element and add the Click Event Listener
    document.getElementById("parent-list").addEventListener("click",function(e) {
        // is our targetted element.
                    // try doing console.log(, it will result LI
        if( && == "LI") {
            console.log( + " was clicked");

Please refer to this write-up on Javascript Event Delegates

Also, below link is the fiddle that I created

hope this helps !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download