7

I want to open links in my post on a new page or a new tab rather. But only the link in the specific division, not all the links on my page. I don't wanna put _blank in all my tags it's too time consuming. How can I do that?

Thanks in advance.

2
  • @ayush specific division means?? you mean certain links. please let me know if they are a href or div clicks.There are multiple ways to do that.
    – kobe
    Commented Nov 12, 2010 at 4:47
  • @ayush , if the answer given by others fixes your problem mark that as answer.So that they will respond fast in future for the questions and help everyone.
    – kobe
    Commented Nov 12, 2010 at 5:20

3 Answers 3

15

With jQuery, you could set the target to _blank for all your links. E.g.

$(function(){
  $("#myDiv a").attr("target","_blank");
});

Example on jsFiddle.

3
  • @ayush you can put the above code in document.ready...so that it will update all the a hrefs
    – kobe
    Commented Nov 12, 2010 at 4:50
  • @gov - Added the doc ready code. I just took it for granted. :) Commented Nov 12, 2010 at 4:54
  • Just a small question this will add target _blank to all links on the div and leave alone the ones that already have it right? It will not add it again if it already have target? Commented Mar 4, 2017 at 15:28
0

You really ought to put them in. If it's too time-consuming, try using a simple regex to do it for you (only run it on the html you care about). Replace:

(<a href[^>]*)(>)

with

$1 target="_blank"$2

If you really need to, you can use JavaScript, but it won't work where javascript is disabled. It's really a terrible solution for this problem:

var el = document.getElementById('myDiv'); // or some other way of making `el` point to your element
var links = el.getElementsByTagName('a');
for( var i = 0; i < links.length; i++ )
{
  links.target = '_blank';
}
1
  • links[i].target = '_blank'; Commented Feb 9, 2022 at 19:07
0

Here is a link to the Javascript that I use to set all the links within a certain div (or all links which are labeled with a certain class) to open in a new window: http://icode4you.net/use-javascript-to-open-all-links-within-a-certain-div-in-a-new-window.

I originally found this script at http://www.dynamicdrive.com/dynamicindex8/newwindow3.htm

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.