javascript - Why doesn't getElementByClassName -> getElementsByTagName -> setAttribute work? -


I want some links to open a new tab. Since I will call it & lt; A & gt; can not be set directly in the tag, so I'm going to & lt; Span & gt; The target attribute via javascript is to keep links in the tag.

I thought it would be easy, but I can not work it:

  addOnloadHook (function () {document.getElementByClassName ('newTab') .getElementsByTagName ( 'A'). SetAttribute ('target', '_blank');}); & Lt; Span class = "newtab" & gt; & Lt; A href = "http://www.com" & gt; Link & lt; / A & gt; & Lt; / Span & gt;  

What am I doing?

document .getElementByClassName does not exist, the correct function is document .getElementsByClassName (additional s note). This gives an array of mailing nodes, so you have to give an index:

  addOnloadHook (function () {document.getElementsByClassName ('newTab') [0] .getElementsByTagName ('a') [0] .setAttribute ('target', '_blank');});  

Comments