Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery `index()` equivalent in Vanilla JS

I have the below code snippet (currentUser class is on a different list item depending on who is viewing the page).

<ul>
    <li>user 1</li>
    <li>user 2</li>
    <li class="currentUser">user 3</li>
    <li>user 4</li>
</ul>

var curLth = jQuery('.currentUser').index();
console.log(curLth); //outputs 2

The site I am working on does not load jQuery, so I want to know which list item has the class currentUser without using jQuery

I have inspected the NodeList in the dev tools but haven't seen anything that I can use to get this.

How can this be achieved?

like image 407
ak85 Avatar asked Jan 30 '15 05:01

ak85


1 Answers

Here is the equivalant:

var curUser = document.getElementsByClassName("currentUser")[0];
var curLth = [].slice.call(curUser.parentNode.children).indexOf(curUser);
console.log(curLth); //outputs 2
like image 97
Vadim Avatar answered Oct 02 '22 01:10

Vadim