javascript - Add target=_blank to every link in a HTML string - Stack Overflow

I have a string s (paragraph of text in HTML format) and I'm using this to include it in a div.doc

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?

Share Improve this question asked Mar 23, 2018 at 10:35 BasjBasj 46.6k110 gold badges456 silver badges807 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

After 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744222297a4563841.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信