简体   繁体   中英

Add target=_blank to every link in a HTML string

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 complicated. Would it be better to add target=_blank after s is inserted in the DOM after .innerHTML = s ? If so, how?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM