最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery `index()` equivalent in Vanilla JS - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited May 28, 2017 at 18:24 Badacadabra 8,4977 gold badges31 silver badges54 bronze badges asked Jan 30, 2015 at 5:07 ak85ak85 4,26419 gold badges71 silver badges114 bronze badges 2
  • 3 possible duplicate of jQuery .index() in javascript – artm Commented Jan 30, 2015 at 5:13
  • @artm thanks for that link. I was having a look around but obviously was using the best search terms – ak85 Commented Jan 30, 2015 at 5:46
Add a ment  | 

1 Answer 1

Reset to default 18

Here is the equivalant:

var curUser = document.getElementsByClassName("currentUser")[0];
var curLth = [].slice.call(curUser.parentNode.children).indexOf(curUser);
console.log(curLth); //outputs 2
发布评论

评论列表(0)

  1. 暂无评论