1

I want to submit a form with JavaScript once any child element of a specific unordered list is clicked.

The code could will look somewhat like this but the number of list items can get very long.

<ul id="myList">
 <li id="myListItem1">list item 1</li>
 <li id="myListItem2">list item 2</li> 
 <li id="myListItem3">list item 3</li>
</ul>

It will not be possible to add an onclick to every li. Also,I may not be able to attach code to the ul tag so if it is possible to solve without attaching code to the ul tag that would be the best. Unfortunately libs like jquery, mootools etc. may not be used. The id of the UL will always be known and static but the id of the LI's will be unknown since they can differ in amount.

djvg
  • 11,722
  • 5
  • 72
  • 103
Blondie
  • 11
  • 1
  • 2

3 Answers3

2

You can do this easily using code such as...

var childNodeArray = document.getElementById('myList').childNodes;

This would give you a array of elements that you can add the click listener to e.g.

for(var node in childNodeArray){
    node.onclick = function () { alert('here'); };
}
NimmoNet
  • 994
  • 2
  • 10
  • 18
  • I'm sorry but I cant get this to work. What would the code look like to have the function alert the ID of the clicked item? `code
    • one
    • two
    • three
    • four
    code`
    – Blondie Apr 19 '11 at 14:06
0

Instead of attaching a listener to each individual <li>, as suggested in nimmonet's answer, you could also use event delegation:

Attach a single event listener to the parent (<ul> in this case), then check the properties of the event.target (i.e. the thing that was clicked) to see what action needs to be taken.

document.getElementById('myList')
  .addEventListener('click', (event) => {
    if (event.target.nodeName.toLowerCase() === 'li') {
      console.log(event.target.textContent + ' clicked');
    }
  });
<ul id="myList">
 <li id="myListItem1">list item 1</li>
 <li id="myListItem2">list item 2</li> 
 <li id="myListItem3">list item 3</li>
</ul>
djvg
  • 11,722
  • 5
  • 72
  • 103