Blondie
Blondie

Reputation: 21

check for click on any child element

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.

Upvotes: 2

Views: 4431

Answers (3)

djvg
djvg

Reputation: 14255

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>

Upvotes: 1

NimmoNet
NimmoNet

Reputation: 994

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'); };
}

Upvotes: 2

Related Questions