0

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?

3
  • 3
    beside the point, but wouldn't it make more sense to just modify the markup? Commented Feb 11, 2016 at 19:32
  • Are you trying to avoid a search&replace? Commented Feb 11, 2016 at 19:41
  • Yeah, in my website has a lot of links, which is very difficult to type it in all the links. Commented Feb 11, 2016 at 19:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!!! It worked. It's because I can't study on a paid place, so what is free I am studying, but it isn't working.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.