Search code examples
javascriptdomevent-handlinggetelementsbytagnamegetattribute

trying to get the href attribute of <a> tag onclick - no errors?


Trying to simply identify if any tags are clicked on at anytime and get the href attribute of the clicked tag to store in the database.

To test i'm attempting to print out the href but nothing is printing on screen AND no errors in console? Any ideas?

// Anchor Tags - Capture the href of the link clicked
var aTags = document.getElementsByTagName('a');

for (var i = aTags.length - 1; i >= 0; --i) {
    aTags[i].onclick = function() {
    var aTagHref = aTags[i].getAttribute("href");
        alert(aTagHref);
    };
}

Solution

  • Inside a event listener you will not have that array of elements, and also, you can use the this to reference the clicked a.

    Like this:

    var aTags = document.getElementsByTagName('a');
    
    for (var i = aTags.length - 1; i >= 0; --i) {
        aTags[i].onclick = function() {
        var aTagHref = this.getAttribute("href");
            alert(aTagHref);
        };
    }
    <a href="#asd">a</a>
    <br />
    <a href="#asdf">b</a>
    <br />
    <a href="#asdfg">c</a>