Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  127] [ 4]  / answers: 1 / hits: 36947  / 10 Years ago, sun, october 5, 2014, 12:00:00

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.


More From » html

 Answers
12

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

[#69236] Thursday, October 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynkarinam

Total Points: 740
Total Questions: 103
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
jaylynkarinam questions
Tue, Jul 23, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Fri, Apr 12, 19, 00:00, 5 Years ago
Wed, Oct 31, 18, 00:00, 6 Years ago
;