Fixing target=”_blank” for W3C compliance using Javascript / jQuery

HTML 4.0 Strict and XHTML 1.0 Strict recommendations of the W3C no longer include the target attribute of the <a> tag. The Transitional versions of the specifications still include it, but by definition, these specs are on the way out.

So this means you can’t use target=”_blank” for your <a> tags if you want to pass the W3C validation. But you can make use of Javascript or jQuery to bypass it.
Here’s the workaround:
1. Use rel=”external” instead of target=”_blank” in your anchor tags
For example:

<a href="http://facebook.com/CompanyProfile" rel="external">Facebook</a>

2. Use Javascript/jQuery code:
Javascript Code:


<script type="text/javascript">
//<![CDATA[
	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;
//]]>
</script>

jQuery Code:


<script type="text/javascript">
	jQuery(function(){
		jQuery('a[rel="external"]').attr("target", "_blank");
	})
</script>

— OR —


<script type="text/javascript">
	jQuery(function(){
		jQuery('a[rel="external"]').click(function(){
			window.open( jQuery(this).attr('href') );
			return false;
		});
	});
</script>

That’s all.
Cheers!