简体   繁体   中英

How to get index value of a link with a specific class using plain JavaScript?

I have about 20 links with a specific class for links I want to target. If the 10th link is clicked, how can I get it's index value (I need "10" to be returned)?

I am using plain JavaScript so no jQuery!

Loop throught the elements, example

function linkOnClick(el) {

    var elements = document.getElementsByClassName('className');
    for (var i = 0; i < elements.length; i++) {
        if (elements[i] == el) {
            alert(i); // index of element
        }
    }
}

You are looking for a getElementsByClassName function. Latest versions of Firefox, Safari and Opera support this but if you want ultimate cross-browser compatibility, I would recommend this function found at: http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/

Then you would loop through the returned elements in a function for the onclick attribute and test if the index matches the index required which you would pass through as a parameter

Exactly as written in the answer by IAbstractDownvoteFactor 正如IAbstractDownvoteFactor在答案中所写的那样

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