How can I alert the id of the item clicked?
- First
- Second
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
$("#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:
you can get the value of the respective li by using this method after click
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;
}
If You Have Multiple li
elements inside an li
element then this will definitely help you, and i have checked it and it works....
<script>
$("li").on('click', function() {
alert(this.id);
return false;
});
</script>