When I was writing (a lot of) <a>
tags I didn't write 'target="_blank"'
, so none of the links are leading to another windows or tag.
Is there a way to add "target='_blank'"
to all the links with JavaScript?
When I was writing (a lot of) <a>
tags I didn't write 'target="_blank"'
, so none of the links are leading to another windows or tag.
Is there a way to add "target='_blank'"
to all the links with JavaScript?
You don't need JavaScript at all. You can use the base
element in your head
to specify a base URL or target for anchors.
<base target="_blank">
will make all links on your page open in new windows and/or tabs.
More information on the base element can be found on MDN.
Previously answered here: How do I add target="_blank" to a link within a specified div?
Code:
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)