admin管理员组文章数量:1291041
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="">Link</a></span>
What am I doing wrong?
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.">Link</a></span>
What am I doing wrong?
Share Improve this question edited Mar 16, 2015 at 18:45 Ben 10.1k5 gold badges42 silver badges42 bronze badges asked Sep 26, 2010 at 12:53 MartinMartin 2,0276 gold badges28 silver badges44 bronze badges2 Answers
Reset to default 8document.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');
});
but you might need to iterate through every span with the specified class ('newTab') on the page for it to work:
addOnLoadHook(function(){
var span = document.getElementsByClassName('newTab');
for(var i in span) {
span[i].getElementsByTagName('a')[0].setAttribute('target','_blank');
}
});
in case you'll have more than 1 anchor tag in a span you'd also have to iterate through the anchor tags like this:
addOnLoadHook(function(){
var span = document.getElementsByClassName('newTab');
for(var i in span){
var a = span[i].getElementsByTagName('a');
for(var ii in a){
a[ii].setAttribute('target','_blank');
}
}
});
版权声明:本文标题:javascript - Why doesn't getElementByClassName -> getElementsByTagName -> setAttribute work? - Stack Overf 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741506791a2382368.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论