replace target=_blank of anchor tag using javascrpt for w3c strict document type
JavaScript Add commentsIf you are using strict mode as your html document type and if you have target=_blank in your html code then wc3 gives you an error. strict mode does not accept target=_blank and they suggest to use transitional mode.
here is the javascript replacement for target=_blank. before this you have to set the rel attribute of anchor tags to “external” or anything you wish because this is used in the javascript code so see which are all the anchor tags has set the rel attribute to external .
in other words you can set the rel attribute with some value to mean that these are the tags which has to be opened in a new window.
<script type="text/javascript"> function target_blank() { var anchors = document.getElementsByTagName("a"); for (var i=0; i<anchors.length; i++) { if ((anchors[i].href!='') && anchors[i].rel == "external") anchors[i].target = "_blank"; } } window.onload = target_blank; </script> |
here is a script with which you can make a single anchor tag open in new window using javascript
<a href="some.html" onclick="window.open(this.href); return false;" onkeypress="window.open(this.href); return false;"> Open in new window using javascript</a> |
…
September 12th, 2010 at 4:37 pm
Thanks for your efforts but it is not working…….
September 29th, 2010 at 10:58 pm
may i know what browser you were using?
August 7th, 2011 at 7:45 pm
The window.onload line is mis-spelled;
traget_blank
Oops!
August 7th, 2011 at 7:57 pm
Also the if statement misses out a dot;
anchor[i]href!=”
should of course be;
anchor[i].href!=”
August 7th, 2011 at 8:10 pm
Also missed out the s in anchor!!
should of course be;
anchors[i].href!”
AND
again in the if statement;
anchor.target = “_blank”
should be;
anchors[i].target = “_blank”;
July 19th, 2012 at 12:33 am
Thanks a lot! It works if change this:
if ((anchor[i]href!=”) && anchor[i].rel == “external”)
anchor.target = “_blank”;
to this:
if (anchors[i].href!=”)
anchors[i].target = “_blank”;
October 2nd, 2012 at 6:13 pm
Your preamble says this:
“all the anchor tags has set the rel attribute to external”
But where did you set the “rel” attribute in your html?
“
Open in new window using javascript”
Should the attribute be set like this:
“
Open in new window using javascript“
October 2nd, 2012 at 6:15 pm
Why did this website convert my html to an external link??? Arrgh… anyway, all I tried to show is that I added “rel=external” to the anchor tag just before the “href”…