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

javascript - Get index of class - Stack Overflow

programmeradmin0浏览0评论

I'm trying to get the index of an element in a class. For example if I have a class called myClass with 5 elements, and the fourth element has an id of fourth, I want to get the index number of #fourth from the class.

I tried using indexOf like this:

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

console.log(myClass.indexOf(fourth));

But I get an error saying:

Uncaught TypeError: myClass.indexOf is not a function

JSFiddle

Code Snippet

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

console.log(myClass.indexOf(fourth));
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass" id="fourth"></div>
<div class="myClass"></div>

I'm trying to get the index of an element in a class. For example if I have a class called myClass with 5 elements, and the fourth element has an id of fourth, I want to get the index number of #fourth from the class.

I tried using indexOf like this:

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

console.log(myClass.indexOf(fourth));

But I get an error saying:

Uncaught TypeError: myClass.indexOf is not a function

JSFiddle

Code Snippet

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

console.log(myClass.indexOf(fourth));
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass" id="fourth"></div>
<div class="myClass"></div>

I then tried creating my own function that gets the index from the class:

function indexInClass(node) {
    var className = node.className;
    var num = 0;
    for (var i = 0; i < className.length; i++) {
        if (className[i] === node) {
            return num;
        }
        num++;
    }
    return -1;
}

But I get undefined when I use it.

How can I get the index of the class?

JSFiddle

Code Snippet

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

function indexInClass(node) {
  var className = node.className;
  var num = 0;
  for (var i = 0; i < className.length; i++) {
    if (className[i] === node) {
      return num;
    }
    num++;
  }
  return -1;
}

console.log(myClass[indexInClass(fourth)]);
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass" id="fourth"></div>
<div class="myClass"></div>

Share Improve this question asked Jan 20, 2016 at 20:38 JessicaJessica 9,83016 gold badges73 silver badges154 bronze badges 5
  • What do you mean via "the index number"? You are using indexOf on a DOM node... – Raffaele Commented Jan 20, 2016 at 20:41
  • @Raffaele, myClass is a collection of DOM nodes, not an individual DOM node. – zzzzBov Commented Jan 20, 2016 at 20:42
  • Not sure, but you might need iterate over myClass and use the .getattribute() to check if the current element has an attribute of 'id' – nocturns2 Commented Jan 20, 2016 at 20:46
  • I know that this is a Javascript question, but just in case anyone's interested you can do something like this with CSS using counters (Codepen demo). Of course, you would only be able to display the result, not access it in javascript. (In this post I showed an example for proof of concept) – Danield Commented Jan 20, 2016 at 21:38
  • @Danield Wow! I did not know that! CSS is more powerful than I thought! Ani rotzeh lishol otcha shala. Ata yachol email me? My email is on my stackoverflow profile. – Jessica Commented Jan 20, 2016 at 23:50
Add a comment  | 

3 Answers 3

Reset to default 10

getElementsByClassName returns an HTML collection, not an array, thus you cannon use indexOf on it.

Iterating over the elements is the way to go, but the problem with your custom function was this:

for (var i = 0; i < className.length; i++) {

You were iterating over className, which is a string containing your node's class name, while instead you should be iterating over your element collection myClass.

Here's your custom function fixed:

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

function indexInClass(node) {
  var className = node.className;
  var num = 0;
  for (var i = 0; i < myClass.length; i++) {
    if (myClass[i] === node) {
      return num;
    }
    num++;
  }
  return -1;
}

console.log(myClass[indexInClass(fourth)]);
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass" id="fourth"></div>
<div class="myClass"></div>


UPDATE

Thanks for the answer! I want to create a function that I can use anywhere, meaning, not specific to myClass. How can I achieve that?

Here's a sligthly optimized version of your function:

function indexInClass(collection, node) {
  for (var i = 0; i < collection.length; i++) {
    if (collection[i] === node)
      return i;
  }
  return -1;
}

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

alert("The ID is: " + indexInClass(myClass, fourth));
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass" id="fourth"></div>
<div class="myClass"></div>


UPDATE 2

Is there a way to do it without the collection argument? For example, is there a way to get the class from the id?

function indexInClass(node) {
  var collection = document.getElementsByClassName(node.className);
  for (var i = 0; i < collection.length; i++) {
    if (collection[i] === node)
      return i;
  }
  return -1;
}

var fourth = document.getElementById('fourth');

alert("The ID is: " + indexInClass(fourth));
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass" id="fourth"></div>
<div class="myClass"></div>

Be careful with .className because it will work properly if the node has one class. If you expect more, you'd need to extract the common one, either from className or classList.

getElementsByClassName returns an HTMLCollection, which does not have the indexOf array methods.

If you have access to Array.from, then the simple solution is to use it to convert the collection to an array and call indexOf:

Array.from(document.getElementsByClassName('myClass'))
    .indexOf(fourth); //3

If you can't use Array.from, then Array.prototype.slice.call should work:

Array.prototype.slice.call(document.getElementsByClassName('myClass'))
    .indexOf(fourth); //3

Your custom function has the right idea, you're just iterating over the wrong variable. Fiddle

var myClass = document.getElementsByClassName('myClass');
var fourth = document.getElementById('fourth');

function indexInClass(node) {
    var className = node.className;
    var num = 0;
    for (var i = 0; i < myClass.length; i++) {
        if (myClass[i] === node) {
            return num;
        }
        num++;
    }
    return -1;
}

console.log(indexInClass(fourth));
发布评论

评论列表(0)

  1. 暂无评论