为什么getElementByClassName - > getElementsByTagName - > setAttribute不起作用?

Mar*_*tin 1 javascript setattribute getelementsbytagname getelementsbyclassname

我想在新标签中打开某些链接.由于我无法将其直接设置到<a>标记中,因此我希望将链接放入<span>具有特定类名的标记中,并通过JavaScript设置目标属性.

我觉得这很容易,但我无法让它工作:

addOnloadHook(function () {
  document.getElementByClassName('newTab').getElementsByTagName('a').setAttribute('target', '_blank');
});

<span class="newTab"><a href="http://www.com">Link</a></span>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Lek*_*eyn 8

document.getElementByClassName不存在,正确的功能是document.getElementsByClassName(注意额外的s).它返回一个匹配节点数组,因此你要给出一个索引:

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