Skip to content Skip to sidebar Skip to footer

Detect Child Node Number

I'm trying to add a event listener for clicking and I want to know the position of the node that was clicked function evl(etna) { document.addEventListener('click', function (e

Solution 1:

function evl(etna){
    document.addEventListener("click",function (el) {
        var clickedElement = el.target || el.srcElement;
        alert("Link detected a click. Cancellable: "+clickedElement.name);
        for(var i = 0; i < etna.length; i++) {
            if(etna[i] === clickedElement) {
                //i is a position of an element in etna
                break;
            }
        }
      },false);
};

You can use this which will point to a clicked element. As to Phil H IE 8 does not work that way. But anyway, there should be used .target or .srcElement. And maybe it will be better to get its id. Name attribute is not valid for divs, spans, etc.

But also you are attaching an event to a document. And this will point to a document. Instead of that you should use el.target || el.srcElement where .target/.srcElement is a pointer to a node where click actually happened.

Also, I do not think you can get index of an element in array (actually, node list) returned by document.getElementsByTagName("*") (well, you can get that list and iterate through it in loop and check each element if it is eaqual to this). Plus, I have no idea why it could be needed.


Solution 2:

Add a loop and set the event listener differently for each item in the etna array:

function evl(etna){
    for(var i=0; i < etna.length; ++i) {
        (function() {
            var thisNode = etna[i];
            var localval = i;
            etna[i].addEventListener("click",function (el) {
                alert("Link detected a click. Cancellable: "+ thisNode.id + " which is id " + localval );
            },false);
        })();
    }
}

Working jsfiddle: http://jsfiddle.net/5xDjE/

The function that is immediately called is merely to force the scoping of thisNode and localval, otherwise all the elements get references to the same variable (javascript scoping is interesting).

I would advise against using the index (scoped via localval) because it requires retaining the original array of nodes. Since nodes change over time and javascript does reference counting for you, you want to avoid these kinds of long arrays of nodes.

Note that this doesn't always have element that was clicked, in IE8 and below this points to the global window object.


Post a Comment for "Detect Child Node Number"