Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get li element onclick with pure javascript without applying onClick to each element

First of all I do not want to use jQuery, just pure javascript; please don't link to duplicate jQuery posts.

If I have a list like

<ul id="bulk">     <li id="one"></li>     <li id="bmw"></li> </ul> 

I want to get the id of the clicked list element. I am aware I could add onClick="" to each element but the production list I have has 2000 entries and I think a better way exists.

For example:

If I had only one li element with id='singular' I could use the following javascript to get the ID clicked.

var li = document.getElementById('singular').onclick = function() { do something }; 

As there are thousands of li elements, this code won't work.

I have been able to get a list of the element names with the following javascript:

var bulk = document.getElementById('bulk'); var bulkli = tabs.getElementsByTagName('li'); //bulkli contains ["one", "bmw"]; 

but this does not tell me which one was clicked.

like image 278
gummage Avatar asked Oct 05 '14 15:10

gummage


1 Answers

You could add an event listener to the parent ul and then use e.target.id to get the id of the clicked element. Just check to make sure that the clicked element is actually an li since it's possible you may not be clicking on one.

Example Here

var ul = document.getElementById('bulk');  // Parent  ul.addEventListener('click', function(e) {     if (e.target.tagName === 'LI'){       alert(e.target.id);  // Check if the element is a LI     } }); 

As pointed out in the comments, this approach won't work when the child of an li is clicked. To solve this, you would need to check to see if the parent element of the clicked element is the one that the click event is attached to.

Example Here

var ul = document.getElementById('bulk'); // Parent  ul.addEventListener('click', function (e) {     var target = e.target; // Clicked element     while (target && target.parentNode !== ul) {         target = target.parentNode; // If the clicked element isn't a direct child         if(!target) { return; } // If element doesn't exist     }     if (target.tagName === 'LI'){         alert(target.id); // Check if the element is a LI     } }); 
like image 83
Josh Crozier Avatar answered Sep 22 '22 22:09

Josh Crozier