In this tutorial we will see how to Select li Tag By Index in JavaScript. The JavaScript getElementsByTagName() method can be used to select li tag by index which returns a NodeList object with all li tags.
Table of Contents
JavaScript getElementsByTagName() method
The JavaScript getElementsByTagName() method returns all HTML elements by tag name as a NodeList object. The NodeList object contains a list of tags. Each individual tag or node can be accessed by index number.
In this example we can also use getElementsByTagName() method to access the li tag by index.
HTML Code
HTML Code is given below, In this code we have a ul tag with four li tags.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Select li By Index</title>
</head>
<body>
<ul id="list">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>PHP</li>
</ul>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code .getElementById is used to select the ul tag, then .getElementsByTagName is used to select all li tags inside ul tag as NodeList object.
Index number [n] is used to select the nth-1 li tag. Where n is index number of li tags from 0 to 3 in this example.
0 is index number of first li while 3 is index number of last li tag.
<script>
var li = document.getElementById("list").getElementsByTagName("li");
li[n].style.color = "blue";
</script>
Select First li Tag
To select first li tag we will use following code.
<script>
var li = document.getElementById("list").getElementsByTagName("li");
li[0].style.color = "blue";
</script>
[0] index number is used to select first li tag.
Select Second li Tag
To select second li tag we will use following code.
<script>
var li = document.getElementById("list").getElementsByTagName("li");
li[1].style.color = "blue";
</script>
[1] index number is used to select second li tag.
Select Third li Tag
To select third li tag we will use following code.
<script>
var li = document.getElementById("list").getElementsByTagName("li");
li[2].style.color = "blue";
</script>
[2] index number is used to select third li tag.
Select Fourth li Tag
To select fourth li tag we will use following code.
<script>
var li = document.getElementById("list").getElementsByTagName("li");
li[3].style.color = "blue";
</script>
[3] index number is used to select fourth li tag.
This is how you can select any li tag by it's index number.
Demo
Video Tutorial
Watch video tutorial on How To Select li By Index in JavaScript.