Sometimes, we want to get the index of an element in JavaScript.
In this article, we’ll look at how to get the index of an element in JavaScript.
How to get the index of an element in JavaScript?
To get the index of an element in JavaScript, we can use the spread operator to spread a node list into an array.
Then we can use the array’s indexOf
method to get the index.
For instance, we write:
const nodes = document.getElementsByTagName('*');
const nodesArr = [...nodes]
const index = nodesArr.indexOf(document.body)
console.log(index)
to select all elements with getElementsByTagName
.
Then we spread the nodes
into an array and assign it to nodesArr
.
Next, we call nodesArr.indexOf
with the element we’re trying to find the index for.
Then we get that the index
is 0 or greater if the element we’re searching for is in the array.
Conclusion
To get the index of an element in JavaScript, we can use the spread operator to spread a node list into an array.
Then we can use the array’s indexOf
method to get the index.