Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get the id/value of <li> element after click function

Tags:

html

jquery

dhtml

How can I alert the id of the <li> item clicked?

<ul id='myid'>   <li id='1'>First</li>   <li id='2'>Second</li>   <li id='3'>Third</li>   <li id='4'>Fourth</li>   <li id='5'>Fifth</li> </ul> 

(Anything that can replace the id may be value or something else will also work.)

like image 502
dave Avatar asked Aug 23 '10 07:08

dave


People also ask

How can get li id value in jQuery?

on('click', function (e) { var id = $(e. target). attr('id'); console. log(id); });

How do I get the clicked element id?

We can get the ID of the element that's clicked from the click event handler. We can either get the value from this if we use a regular function. Or we can get the same value from the event object of the click event handler.

How do I know which ID is clicked in jQuery?

You can just utilize the jQuery attr() strategy to get or set the ID property estimation of a component. The accompanying model will show the ID of the DIV component in an alarm box on a button click.


2 Answers

$("#myid li").click(function() {     alert(this.id); // id of clicked li by directly accessing DOMElement property     alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose     alert($(this).html()); // gets innerHTML of clicked li     alert($(this).text()); // gets text contents of clicked li }); 

If you are talking about replacing the ID with something:

$("#myid li").click(function() {     this.id = 'newId';      // longer method using .attr()     $(this).attr('id', 'newId'); }); 

Demo here. And to be fair, you should have first tried reading the documentation:

  • http://api.jquery.com/category/selectors/
  • http://api.jquery.com/category/events/
  • http://api.jquery.com/attr/
like image 199
karim79 Avatar answered Sep 24 '22 13:09

karim79


If you change your html code a bit - remove the ids

<ul id='myid'>   <li>First</li> <li>Second</li> <li>Third</li> <li>Fourth</li> <li>Fifth</li> </ul> 

Then the jquery code you want is...

$("#myid li").click(function() {     alert($(this).prevAll().length+1); });​ 

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

  • jQuery prevAll
like image 20
vikmalhotra Avatar answered Sep 22 '22 13:09

vikmalhotra