Search code examples
htmlanchorxhtml-1.0-strict

Make HTML anchor to a new window in a strict docktype


We use "target" attribute of the tag to specify the target location of the link.

But "target" attribute cannot be used in strict doctype (I referred this at http://w3schools.com/tags/tag_a.asp). So what is the solution if we use strict doctype?


Solution

  • In short, JavaScript.

    The strict doctype is loosely considered to be "strictly document content" and not behaviour, which the target attribute defines. It assumes the user will decide and have complete control over how links are opened in their browser.

    The solution is to use JavaScript to define how links open. You might use a class or other attribute to have a JS library to force them to open in a new window:

    <a href="test.php" rel="external">my link</a>
    

    So your script might look like this:

    function externalLinks() {
        if (!document.getElementsByTagName) return;
        var anchors = document.getElementsByTagName("a");
        for (var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if (anchor.getAttribute("href") &&
            anchor.getAttribute("rel") == "external")
            anchor.target = "_blank";
        }
    }
    window.onload = externalLinks;
    

    This is even easier in jQuery:

    $(function(){
      $('a[rel=external]').attr('target', '_blank');
    });