5

I'm trying to come up with a solution that will allow me to know whenever an "A" tag (or any other tag within an "A" tag) is clicked.

For example:

<a href="#">Link 1</a>
<a href="#"><span>Link 2</span></a>
<a href="#"><img src="#">Link 3</img></a>

So far I have this:

<script>
document.getElementsByTagName("BODY")[0].addEventListener('click', function(e) {
if(e.target && e.target.tagName == "A") {
console.log(e.target.text); }
}, false);
</script>

This is returning the text for link 1, but not for links 2 and 3. I also do not want to get any text if someone clicks on span or img elements that dont have an anchor tag.

2 Answers 2

8

Legacy Browsers

.target returns the element that was clicked on. In the case of link 2, this will always be the span tag; on a properly formed version of link 3 sometimes it would be the a tag, sometimes it would be the img tag depending where you click. In order to figure out if the .target is inside of an a tag you need to climb up the DOM tree using parentNode until you reach an a node or the document itself, which has a .parentNode of null.

var getParentAnchor = function (element) {
  while (element !== null) {
    if (element.tagName && element.tagName.toUpperCase() === "A") {
      return element;
    }
    element = element.parentNode;
  }
  return null;
};

document.querySelector("body").addEventListener('click', function(e) {
  var anchor = getParentAnchor(e.target);
  if(anchor !== null) {
    console.log(anchor.textContent);
  }
}, false);
<a href="#">Link 1</a>
<a href="#"><span>Link 2</span></a>
<a href="#"><img src="example.jpg">Link 3</a>
<div>
Non link text
</div>

The standard .textContent should be preffered over .text.

It's easier to use querySelector to grab the body, unless you need to support IE7 or less.

Modern Browsers

If you don't need to support older browsers like IE or Opera mini, the code can be simplified by using the Element.closest method. You can completely get rid of the getParentAnchor and replace it with a single .closest call, shortening the code quite a bit:

document.querySelector("body").addEventListener('click', function(e) {
  var anchor = e.target.closest('a');
  if(anchor !== null) {
    console.log(anchor.textContent);
  }
}, false);
<a href="#">Link 1</a>
<a href="#"><span>Link 2</span></a>
<a href="#"><img src="example.jpg">Link 3</a>
<div>
Non link text
</div>

4
  • 1
    element.tagName is undefined for when while loop reaches at document. This occurs in case of the click e.target doesn't have parent anchor. Here is the updated version:
    – Zahid
    Feb 21, 2020 at 23:07
  • 1
    var getParentAnchor = function (element) { while (element !== null && !(element instanceof HTMLDocument)) { console.log(element); if (element.tagName.toUpperCase() === "A") { return element; } element = element.parentNode; } return null; };
    – Zahid
    Feb 21, 2020 at 23:07
  • 1
    @Zahid Thanks for mentioning the bug, I don't know how I missed your comment earlier. I took a different approach to patching it. Since calling the toUpperCase method of the non-existent element.tagName property was causing the problem, I test for the existence of tagName before calling its method, if (element.tagName && element.tagName.toUpperCase() === "A"). Mar 25, 2021 at 7:51
  • Please note that attaching an event listener to document.body only works for those events that "bubble up" the DOM tree. For example, mouseover and mouseout are such events, but mouseenter and mouseleave do not bubble out, so event.target will always be document.body. See developer.mozilla.org/en-US/docs/Web/API/Element/… for the explanation for the difference between mouseenter and mouseover.
    – tst
    Sep 14, 2022 at 1:56
1
[].forEach.call(document.getElementsByTagName("a"),function(el){
  el.addEventListener("click",function(e){
    console.log(el.text);
  });
});

This code will just do the work for you. This will give attach click event to all the a tags. You can el.text to target text inside a.

2
  • 2
    Adding a separate event handler to each anchor on the page is extremely inefficient. If the page has a lot of links on it that could add a lot of unnecessary overhead. Event delegation is much more suitable for this situation. Nov 12, 2014 at 5:46
  • Moreover, it does not reflect changes in the DOM tree: meaning that newly & dynamically created <a> tags wouldn’t benefit from this. Jan 21, 2022 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.