简体   繁体   中英

Get index of class clicked in JavaScript. No jQuery

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?

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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM