0

Do not undertand why I can not get the attribute value of tag element by using function getElementsByTagName.

Also I have no problems with using direct acsess to the element by id , like t.getAttribute('href') from <a id="t">.</a>

 var a = document.body.getElementsByTagName('a').getAttribute('href');
    console.log(a);
 <a href="###">http://internal.com/</a>
Sviat Kuzhelev
  • 1,758
  • 10
  • 28
  • `var a = document.body.getElementsByTagName('a')[0].getAttribute('href');` or `var a = document.body.querySelector('a').getAttribute('href');` Note the plural **"elements"** in the method name. See the linked question's answers for details. :-) – T.J. Crowder Jan 18 '18 at 10:54

1 Answers1

2

getElementsByTagName will return a array so put the index and get the element you want

 var a = document.body.getElementsByTagName('a')[0].getAttribute('href');
    console.log(a);
<!DOCTYPE HTML>
<html>

<head>
</head>

<body>
    <a href="###">http://internal.com/</a>
</body>

</html>
zabusa
  • 2,520
  • 21
  • 25
  • I had simplified this code. i need it work to an array of **a** tags. The loop is not working (( `var a = document.body.getElementsByTagName('a'); for (var i = 0; i , a.length; i++) { a[i].getAttribute('href'); }` – Sviat Kuzhelev Jan 18 '18 at 10:56
  • will update the answer – zabusa Jan 18 '18 at 11:00