JQuery get id / value of <li> element after click function
How can I warn the <li> id of the <li> element?
<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 an identifier can matter or something else.)
+65
dave Aug 23 '10 at 7:03 2010-08-23 07:03
source share4 answers
$("#myid li").click(function() { alert(this.id); // id of clicked li by directly accessing DOMElement property alert($(this).attr('id')); // jQuery .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 identifier with something:
$("#myid li").click(function() { this.id = 'newId'; // longer method using .attr() $(this).attr('id', 'newId'); }); Demo is here. And honestly, you should first try reading the documentation:
+128
karim79 Aug 23 '10 at 7:05 2010-08-23 07:05
source shareIf you change your HTML code a bit, remove the identifiers
<ul id='myid'> <li>First</li> <li>Second</li> <li>Third</li> <li>Fourth</li> <li>Fifth</li> </ul> Then the jquery code you need ...
$("#myid li").click(function() { alert($(this).prevAll().length+1); }); You do not need to post any identifiers, just keep adding li elements.
Take a look at the demo
useful links
+11
vikmalhotra Aug 23 '10 at 7:20 2010-08-23 07:20
source shareYou can get the value of the corresponding li using this method after clicking
HTML: -
<!DOCTYPE html> <html> <head> <title>show the value of li</title> <link rel="stylesheet" href="pathnameofcss"> </head> <body> <div id="user"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <ul id="pageno"> <li value="1">1</li> <li value="2">2</li> <li value="3">3</li> <li value="4">4</li> <li value="5">5</li> <li value="6">6</li> <li value="7">7</li> <li value="8">8</li> <li value="9">9</li> <li value="10">10</li> </ul> <script src="pathnameofjs" type="text/javascript"></script> </body> </html> JS: -
$("li").click(function () { var a = $(this).attr("value"); $("#user").html(a);//here the clicked value is showing in the div name user console.log(a);//here the clicked value is showing in the console }); CSS: -
ul{ display: flex; list-style-type:none; padding: 20px; } li{ padding: 20px; } 0
Sandeep Mukherjee Sep 18 '18 at 17:49 2018-09-18 17:49
source shareIf you have multiple li elements inside the li element then this will definitely help you, and I checked this and it works ....
<script> $("li").on('click', function() { alert(this.id); return false; }); </script> -3
RaghuVamshiKrishna Boine Jan 17 '17 at 10:56 on 2017-01-17 10:56
source share