3

Edit: The suggestion points to a jquery answer, which I would prefer not to use. I may have done a bad job explaining this. When you click on a class, I want to know which one it is of all the classes sharing that same name. For instance, if there are 8 buttons on the page with a classname of 'mybutton', when I click on one, I want to know which index it was ex: mybutton[3].

Original Post: Is there a simple way to get the index of the class you clicked? I can't seem to find anything in the MouseEvent obj. I have searched stackoverflow/internet but what I can find seems to be over complicated,unanswered, or using jQuery. Example:

document.body.addEventListener('click',function(event){
        console.log(event.target.className);
        console.log(event.target.className.index??)`
    });

I feel like it should be simple, no?

10
  • 2
    What do you mean by the "index of the class?" Commented Oct 30, 2015 at 20:33
  • Did you mean Index of element with some specific class-name? Commented Oct 30, 2015 at 20:34
  • If the linked question isn't really what you were asking, please clarify what you mean by "the index of the class". Commented Oct 30, 2015 at 20:41
  • @divy3993 Yes I am looking to know the index of the element. Commented Oct 30, 2015 at 20:48
  • @Pointy Yes the answer is not really what I was asking for. I revised the question to try and better explain my desired result. Commented Oct 30, 2015 at 20:50

1 Answer 1

4

There's no "easy" way to do it; that is, the DOM API doesn't directly answer that sort of question. You can however simply search through the list of elements that match any characteristic you want and see which one your element matches:

function indexIn(selector, element) {
  var list = document.querySelectorAll(selector);
  for (var i = 0; i < selector.length; ++i)
    if (list[i] === element) return i;
  return -1;
}

Then your handler can look through the .classList on the clicked element:

document.body.addEventListener('click',function(event){
  for (var i = 0; i < this.classList; ++i)
    console.log("index for class " + this.classList[i] + ": " +
      indexIn("." + this.classList[i], this));
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sticking with me @pointy. I wasn't sure if I there was a simpler way to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.