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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744222297a4563841.html
评论列表(0条)