8

Look this code:

<div>
    <a href = "#"><span>Click me MAN !</span></a>
</div>

<script type = "text/javascript">
    window.onload = function () {
        document.body.addEventListener ("click", function (event) {
            var target = event.target;

            alert ("Returns \"" + target.nodeName + "\". Just want \"" + target.parentNode.nodeName + "\"")
        }, false);
    }
</script>

You can see the element "span" inside a "link", when the "link" is clicked the current target is the same "span". How can the "event.target" return "link" instead of "span".

Thanks and no, I don't want to use "parentNode".

Caio
  • 3,178
  • 6
  • 37
  • 52
  • 4
    Why exactly are you listening for a click on the body instead of just targeting the anchor tag? –  Jan 10 '11 at 00:54
  • @Matt: It's a good idea to reduce event handlers to a minimum and use the fact that most events bubble up the DOM tree, a technique known as *event delegation*. This may be what the OP is doing. – Tim Down Jan 10 '11 at 10:07

3 Answers3

9

With your approach, you either have to manually traverse up the DOM until you hit an <a> element or attach the listener to the link itself and use this.

Minimizing the number of event listeners is generally a good idea, so here's an example of how to traverse the DOM. Note that the event listener will not work in IE, which does not support the addEventListener() method of DOM nodes.

Live example: http://jsfiddle.net/timdown/pJp4J/

function getAncestor(node, tagName) {
    tagName = tagName.toUpperCase();
    while (node) {
        if (node.nodeType == 1 && node.nodeName == tagName) {
            return node;
        }
        node = node.parentNode;
    }
    return null;
}

document.body.addEventListener("click", function(event) {
    var target = getAncestor(event.target, "a");
    if (target !== null) {
        alert(target.nodeName);
    }
}, false);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
5

Add the this css tips for JavaScript. You will get event.target you want.

a > *,
button > *{
  pointer-events:none;
}
piayo
  • 101
  • 2
  • 4
0

Can't you just use

<span><a href="#">Click me</a></span> ?
Cray
  • 2,396
  • 19
  • 29
  • What is the point of the span then? It becomes completely useless. –  Jan 10 '11 at 00:57
  • How to you figure? The styles aplpied on it are still valid for the contents of the link... – Cray Jan 10 '11 at 14:28