[Solved] Call javascript function by clicking on HTML list element [closed]


This will hopefully get you going in the right direction. All I’m doing is binding an “onClick” event listener to all li elements, you might want to change what you bind to in case you use them elsewhere. Then when they are clicked they call the function myScript which get’s their ID and alerts it.

JSFiddle Demo

HTML

<ul>
    <li id="1">Link 1</li>
    <li id="2">Link 2</li>
    <li id="3">Link 3</li>
    <li id="4">Link 4</li>
    <li id="5">Link 5</li>
</ul

Javascript

var li = document.getElementsByTagName("li");

for(var i = 0;i<li.length;i++){
    li[i].addEventListener("click", myScript);
}

function myScript(e){
    alert(e.target.attributes.id.value);       
}

0

solved Call javascript function by clicking on HTML list element [closed]