I have 3 divs with class: wpEdit and onClick: alertName()
<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>
When clicked i want to know the Index of class wpEdit of the clicked Div:
function alertName(){
    //Something like this
    var classIndex = this.className.index; // This obviously dosnt work
    alert(classIndex); 
}
when clicked on Bruce Lee it should alert : 0 when clicked on Jackie Chan it should alert : 1 when clicked on Jet Li it should alert : 2
I need to know which instance of class="wpEdit" is clicked on
Try this
function clickedClassHandler(name,callback) {
    // apply click handler to all elements with matching className
    var allElements = document.body.getElementsByTagName("*");
    for(var x = 0, len = allElements.length; x < len; x++) {
        if(allElements[x].className == name) {
            allElements[x].onclick = handleClick;
        }
    }
    function handleClick() {
        var elmParent = this.parentNode;
        var parentChilds = elmParent.childNodes;
        var index = 0;
        for(var x = 0; x < parentChilds.length; x++) {
            if(parentChilds[x] == this) {
                break;
            }
            if(parentChilds[x].className == name) {
                index++;
            }
        }
        callback.call(this,index);
    }
}
Usage:
clickedClassHandler("wpEdit",function(index){
    // do something with the index
    alert(index);
    // 'this' refers to the element 
    // so you could do something with the element itself
    this.style.backgroundColor = 'orange';
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With