replace target=_blank of anchor tag using javascrpt for w3c strict document type

JavaScript Add comments

If 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>

8 Responses to “replace target=_blank of anchor tag using javascrpt for w3c strict document type”

  1. Govind Saini Says:

    Thanks for your efforts but it is not working…….

  2. admin Says:

    may i know what browser you were using?

  3. Harry Alffa Says:

    The window.onload line is mis-spelled;
    traget_blank

    Oops!

  4. Harry Alffa Says:

    Also the if statement misses out a dot;
    anchor[i]href!=”

    should of course be;
    anchor[i].href!=”

  5. Harry Alffa Says:

    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”;

  6. webnut Says:

    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”;

  7. Bubba Says:

    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

  8. Bubba Says:

    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”…

Leave a Reply

Entries RSS