There is such code:

let l = document.getElementsByTagName("a"); for (k in l){ l[k].onclick = function(){ alert(this.href); return false; } } 

It should output the address of the link, I get undefined. Tried it like this:

 let l = document.getElementsByTagName("a"); for (k in l){ l[k].onclick = function(){ alert(l[k].href); return false; } } 

The result is the same. Tell me what am I doing wrong?

4 answers 4

To get the attribute value of an element, use getAttribute . In your case, the code will look like this:

 let l = document.getElementsByTagName("a"); for (k in l){ l[k].onclick = function(){ alert(this.getAttribute('href')); return false; } } 
  • Everything works great, thank you. - Gazro

The first example works this way, and secondly, you missed the initialization of a variable, as in the first, but unlike the first, and the second, you would need to place the var in place to select let more here answer Grundy

 let l = document.getElementsByTagName("a"); for (let k in l) { l[k].onclick = function() { alert(l[k].href); return false; } } 
 <a href="https://ya.ru">https://ya.ru</a> <a href="https://google.com">https://google.com</a> 

  • Well, at least in one answer, they did not forget about the initialization of the variable in the loop, however, it is probably more correct to use not let in both cases, but const - MedvedevDev

It all works:

 let l = document.getElementsByTagName("a"); for (k in l) { l[k].onclick = function() { console.log(this.href); return false; } } 
 <a href="http://google.com" id="ttt">test</a> <a href="http://go123ogle.com" id="tt23t">test2</a> 


maybe your code is executed before loading the whole document?

    I think that in this case it is better to use for..of

     for (let anchor of document.getElementsByTagName("a")) { anchor.addEventListener('click', doNothing); } const doNothing = e => { console.log(e.target.getAttribute('href')); }