Why doesn't getElementByClassName -> getElementsByTagName -> setAttribute work?
11,561
document.getElementByClassName
does not exist, the correct function is document.getElementsByClassName
(note the extra s
). It returns an array of matching nodes, so you've to give an index:
addOnloadHook(function () {
document.getElementsByClassName('newTab')[0].getElementsByTagName('a')[0].setAttribute('target', '_blank');
});
![Martin](https://i.stack.imgur.com/Zbb5Z.gif?s=256&g=1)
Author by
Martin
Updated on June 22, 2022Comments
-
Martin about 2 years
I want open certain links in a new tab. Since I can't set it directly into the
<a>
tag, I want to put the link into<span>
tags with a certain class name and set the target attribute via JavaScript.I thought this would be easy, but I can't get it working:
addOnloadHook(function () { document.getElementByClassName('newTab').getElementsByTagName('a').setAttribute('target', '_blank'); }); <span class="newTab"><a href="http://www.com">Link</a></span>
What am I doing wrong?