Brief
What you are trying to do is called event delegation. You want to listen to the event from the parent <div>
for events bubbling up from the child <a>
tags.
You can delegate the event by using jQuery's .on()
function:
var link = document.getElementById('mapSelections');
$(link).on('click', 'a', function () {
var text = $(this).text();
//console.log(text);
alert(text);
});
Explanation
Basically there are two options for what you want:
Multiple Listeners
$("#mapSelections a").on('click', function () {
var text = $(this).text();
alert(text);
});
This works fine but you are binding event listeners to several elements (one listener to each <a>
tag). There is a bit of overhead for each one so it's not the most performant option available to you.
Event Delegation
$("#mapSelections").on('click', 'a', function () {
var text = $(this).text();
alert(text);
});
The reason (IMO) this is best is because you are saving your application some resources. You are binding only one listener to the parent $("#mapSelections")
, and that element is then waiting for events that bubble up only from child <a>
tags.