55341

returning clicked li class in an ul javascript/jquery

Question:

My code (the html page):

<nav> <ul> <li id="homeLink"><a href="#">Home</a></li> <li id="rekenLink"><a href="#">Rekenmachine</a></li> <li id="bakkerLink"><a href="#">Parkeergarage</a></li> <li id="garageLink"><a href="#">Bij de bakker</a></li> <ul> </nav>

The javascript/jquery behind it:

$(function () { $("ul").click(function () { // here I want to get the clicked id of the li (e.g. bakkerLink) }); });

How do I do that?

Answer1:

Use the <a href="http://api.jquery.com/on/" rel="nofollow">.on()</a> method with signature $(common_parent).on(event_name, filter_selector, event_listener).

<h2>Demo: <a href="http://jsfiddle.net/gLhbA/" rel="nofollow">http://jsfiddle.net/gLhbA/</a></h2> $(function() { $("ul").on("click", "li", function() { // here I want to get the clicked id of the li (e.g. bakkerLink) var id = this.id; alert(id); }); });

Another method is to bind the event to li instead of ul:

$(function() { $("li").click(function() { // here I want to get the clicked id of the li (e.g. bakkerLink) var id = this.id; alert(id); }); });

Answer2:

Use jQuery on() instead of click and pass li as selector.

$(function() { $("ul").on('click', 'li', function() { //Here this will point to the li element being clicked alert(this.id); }); });

on() reference - <a href="http://api.jquery.com/on/" rel="nofollow">http://api.jquery.com/on/</a>

Answer3:

$(function() { $("li").click(function() { alert(this.id); }); });

edit: <a href="http://jsfiddle.net/j5gky/" rel="nofollow">jsfiddle link</a>

Answer4:

Handle the click event of the <li> instead of the <ul>.<br /> You can then get this.id.

Answer5:

Use the event's target (The anchor that was clicked) and then grab its parent's id:

$(function() { $("ul").click(function(e) { alert(e.target.parentNode.id); }); });

<a href="http://jsfiddle.net/9JfG2/" rel="nofollow"><strong>JSFiddle</strong></a>

Answer6:

here is one of the way to do. Make sure your using the latest jquery file.

$("ul li").on('click', function() { console.log($(this).attr("id")); });

Answer7:

You may try

$(function () { $("li").click(function () { var id = $(this).attr("id"); alert(id); }); });

or

$(document).ready( function() { $("li").click(function () { var id = $(this).attr("id"); alert(id); }); });

Recommend