September 21, 2008 10:18 am GMT

XHTML Strict incompatible with target attribute: FALSE

by Gary Illyes



Clients… I had to create a website… XHTML Strict… AND opening all links in a new tab/window.
No probs, there’s the target attribute of the anchor elements! But not in XHTML Strict!
W3 states clearly that target attributes should be forgotten and avoided. Why, I have no idea, but if you want to create XHTML Strict pages, you can forget about the target attribute.

So let’s hack with Javascript this rule! Rules are set to have something to brake, that’s what we’ll do now. This is very simple code, basically a single function which loops through the document and adds to all the anchor elements the “target=’_blank’” attribute. As it’s created with Javascript, the XHTML validators should not observe. I think they won’t observe, so first check it out somewhere.

So, the Javascript code to open links in new window/tab while maintaining the XHTML Strict compliance is:

function open_in_new_tab() {
if (!document.getElementsByTagName){
return;
/*If the browser doesn't support DOM, do nothing*/
}
var anchors = document.getElementsByTagName("a");
/*Select all the 'a' tags, anchors*/
for (var i=0; i<anchors.length; i++) {
var links = anchors[i];
if (links.getAttribute("href")){
/*every anchor with 'href' attribute will get a new attribute,
only those with 'href' attribute set because we don't want
to mess with the section anchors, for example*/
links.target = "_blank";
}
}
}
window.onload = open_in_new_tab;
/*finally load the function on page load*/

And the word is saved again.


Comments

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

If you want to use your OpenID, fill out the field labeled "Website" with the OpenID URL. The other fields may remain empty.
Note that comments are pre-moderated.

Subscribe without commenting