Validating XHTML and the target attribute

You may not have realised but XHTML doesn’t support the target attribute of the <a> tag.

For example, this code:

<a href="blabla.html" target="_blank">Bla bla</a>

Would not validate as the "target"attributewas left out of the XHTML specification. This code is meant to open up a new window when the user clicks on the link.

The only way so solve this is to use JavaScipt in one of two ways.

The first is to add lots of things to the a tag to get the tag to open in another window. This is a bit messy, but generally works. The trick is to remember to put all of this code every time you want a link to open in a new window.

<a href="http://www.norton42.org.uk" onclick="window.open(this.href); return false;" onkeypress="window.open(this.href); return false;">Norton42.org.uk</a>

As the first method is a bit messy the other solution is to drop the target attribute and use the rel attribute with the value of external. Like this:

<a rel="external" href="http://blahblah.com">new link</a>

Using this attribute you can then use a Javascript method to replace all of the rel attributes with target attributes.

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;

With the rel attribute the XHTML validates, and the JavaScript allows the <a> tags to open in another window. Although what we are doing here is getting JavaScript to replace the code on the site, and this seems a little cheeky to me. However, if a user doesn´t have JavaScript then they won´t see any funny effects.

Discussion Area - Leave a Comment




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>