简体   繁体   中英

HTML Add attribute on an element

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. :-)

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