How To Get The Selected LI's Index From An UL Using Javascript
In This Javascript Tutorial we will See How To Get The Selected <li> Item From An Unordered List <ul> And Display The Index Value On LI Click Using Array In JS And Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript: get selected LI index</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<ul id="list">
<li>JS</li>
<li>PHP</li>
<li>Java</li>
<li>C#</li>
<li>c++</li>
<li>HTML</li>
<li>CSS</li>
</ul>
<script>
var items = document.querySelectorAll("#list li"),
tab = [], index;
// add values to the array
for(var i = 0; i < items.length; i++){
tab.push(items[i].innerHTML);
}
// get selected element index
for(var i = 0; i < items.length; i++)
{
items[i].onclick = function(){
index = tab.indexOf(this.innerHTML);
console.log(this.innerHTML + " Index = " + index);
};
}
</script>
</body>
</html>
OUTPUT:
3 comments
commentsHa, I have written similar solution but it has one minus when you create a to do list where li is an complex object it is not so easy, as I can see there is no simple solution for this. I hoped i can find node count or something in clean javascript.
ReplyGreat post, I have a few examples of using splice if you are interested!
Replyvar months = ['Jan', 'March', 'April', 'June'];
// Insert 'Feb' at 1st index position
months.splice(1, 0, 'Feb');
console.log(months);
// Result: ['Jan', 'Feb', 'March', 'April', 'June']
// Replace 'June' with 'May' at the 4th index position
months.splice(4, 1, 'May');
console.log(months);
// Result: ['Jan', 'Feb', 'March', 'April', 'May']
// Remove 'May' from the 4th index position
months.splice(4, 1);
console.log(months);
// Result: ['Jan', 'Feb', 'March', 'April']
// Remove 'Feb' & 'March' from the 1st & 2nd index positions
months.splice(1, 2);
console.log(months);
// Result: ['Jan', 'April']
Thanks a lot bro
Reply