-1

I using javascript in js file like this:

document.body.onclick = function(ev) {
    alert(this.getAttribute("href"));
};

but that code gave me null.

I don't want using jQuery. for example $(this).attr('href');

Do you got any better suggest? I want get last href when user click on any <a> tags.

Mikel Williams
  • 417
  • 5
  • 20

3 Answers3

2

What you’re trying to do is called event delegation, however, you’re trying to access the clicked element via this. This might work in jQuery, but in regular JavaScript events (e.g. by binding to the onclick property or by using addEventListener) this refers to the object you’re binding the event to, i.e. in code like this, this always refers to <body>:

document.body.onclick = function(ev) {
  console.log("onclick variant — `this` is", this);
};

document.body.addEventListener("click", function(ev) {
  console.log("addEventListener variant — `this` is", this);
});
<div>Click me to see what <code>this</code> refers to.</div>

To see which element actually has been clicked, in a nutshell, you need ev.target:

document.body.onclick = function(ev) {
  console.log("onclick variant — `ev.target` is", ev.target);
};

document.body.addEventListener("click", function(ev) {
  console.log("addEventListener variant — `ev.target` is", ev.target);
});
<div>Click me to see what <code>this</code> refers to.</div>

Use addEventListener, since this is more modern and allows binding more than one event listener and provide more control over event propagation.

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
0

You might wanted to write something like this:

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', function () {
        alert(this.href);
    });
}

Note:
this.getAttribute('href'); works as well, but –as stated in the comments– you were selecting one item, document.body, which has no href attribute.

dferenc
  • 7,163
  • 12
  • 36
  • 42
0

You code worked, but body have not href attribute. But use like this:

var elems = document.querySelectorAll("a")
var onClick = function (event) {
    alert(event.target.getAttribute("href"));
}
elems.forEach((el) =>{
    el.addEventListener("click", onClick);
});