I would like to know how I can refer to a list item object if I had for example the following html list
<div id='subdiv_2'> <div id='subdiv_3'> <ul> <li><a href=''>Item1</a></li> <li><a href=''>Item2</a></li> <li><a href=''>Item3</a></li> </ul> </div> </div>
How is it possible to register an onclick to the Item2 li without it having to have a unique elementId eg I can do so for subdiv_3 because it has a unique ID and isn’t in the list by
document.getElementById('subdiv_3').addEventListener('click', function();, false);
My goal is ultimately to assign a function to each list object, for the number of list objects with unique parameters based upon the list object number eg:
for(i=0;i<list.length;i++){ 'document.getElementById(list.item'+i+').addEventListener(\'click\',function('+i+');,false);'; }
You could get all the children elements of
subdiv_3that are<li>. Then iterate through that loop adding the functions as you go.Looking at your code sample, when you’re in the loop creating your functions you may run into closure scoping problems. (All the functions will appear to use the same value of i.) Check out my answer to this question to deal with that problem: How to Add Event Handler with Arguments to an Array of Elements in Javascript?