Question

I'm trying to get the text value of a list item in an unordered list when the items is clicked on.

I've added an event listener and am logging the results to the console before I go any further.

When I selected by class I received only one line item, but it didn't matter which link you clicked it showed the same link text. I've tried using .eq(), this, and a few other methods but either way I either return all 4 elements or no elements

Here is my fiddle.

HTML:

<div id="mapSelections"> 
<ul>
    <li>Jump to State : </li>
    <li id="Conn" ><a href="#">Connecticut</a> |</li>
    <li id="Maine"><a href="#">Maine</a> |</li>
    <li id="Mass"><a href="#">Massachusetts</a> |</li>
    <li id="Rh"><a href="#">Rhode Island</a> |</li>
    <li id="Home"><a href="#">Home</a></li>
</ul>

And here is the listener:

var link = document.getElementById('mapSelections');
link.addEventListener('click', function () {
   var text = $("li:eq()", this).text();
   console.log(text);
});
Was it helpful?

Solution

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

Here is updated fiddle.

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.

OTHER TIPS

Like this? http://jsfiddle.net/q8nzR/1/

I just edited a few lines of your jQuery:

$('#mapSelections a').on('click', function () {


    var text = $(this).text();
    console.log(text);
    //alert(text);
});

Your problem was, that THIS was not reffering to a single a, but the whole div#mapSelections instead.

You should bind the handler to the LI, not the whole DIV.

$("#mapSelections li").click(function() {
    var text = $(this).find("a").text();
    console.log(text);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top