admin管理员组文章数量:1400115
I have a string s
(paragraph of text in HTML format) and I'm using this to include it in a div
.
document.getElementById("mydiv").innerHTML = s;
s
might contain a few <a href="...">...</a>
links. How to automatically add target="_blank"
to these links? (so that if the user clicks on them, it won't replace the current page)
I was thinking about using some kind of regex to detect links in s
, detect if target=_blank is already present, and if not, add it, but this seems plicated.
Would it be better to add target=_blank
after s
is inserted in the DOM after .innerHTML = s
? If so, how?
I have a string s
(paragraph of text in HTML format) and I'm using this to include it in a div
.
document.getElementById("mydiv").innerHTML = s;
s
might contain a few <a href="...">...</a>
links. How to automatically add target="_blank"
to these links? (so that if the user clicks on them, it won't replace the current page)
I was thinking about using some kind of regex to detect links in s
, detect if target=_blank is already present, and if not, add it, but this seems plicated.
Would it be better to add target=_blank
after s
is inserted in the DOM after .innerHTML = s
? If so, how?
2 Answers
Reset to default 6After adding anchors with innerHTML
, iterate through all the anchors with querySelectorAll()
. Then set the target
attribute with setAttribute()
like the following:
document.querySelectorAll("#mydiv a").forEach(function(a){
a.setAttribute('target', '_blank');
})
Would it be better to add target=_blank after s is inserted in the DOM after .innerHTML = s? If so, how?
After doing the innerHTML
document.getElementById("mydiv").innerHTML = s;
Iterate all the link a
inside myDiv
and set this attribute target
to them
var myDivEl = document.getElementById( "mydiv" ); //get the reference to myDiv element
var anchorsInMyDiv = myDivEl.querySelectorAll( "a" ); //get all the anchors in myDiv element
[ ...anchorsInMyDiv ].forEach( s => s.setAttribute( "target", "_blank" ) ); //iterate all the anchors and set the attribute
本文标签: javascriptAdd targetblank to every link in a HTML stringStack Overflow
版权声明:本文标题:javascript - Add target=_blank to every link in a HTML string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744222297a2595925.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论