Adding W3C validation icons with JavaScript

Adding a W3C validation icon to our pages can be quite a tedious task. So why don't we add such validation icons by using JavaScript? For example, given this demo page, we have a basic Wordpress template with the following two links:

<li><a href="http://validator.w3.org/check/referer" title="This page validates as XHTML 1.0 Strict">Valid <acronym title="eXtensible HyperText Markup Language">XHTML</acronym></a></li>
   <li><a href="http://jigsaw.w3.org/css-validator/check/referer" title="This page uses valid CSS">Valid <acronym title="Cascading Style Sheets">CSS</acronym></a></li>

We want to change the content of each link with a validation icon. Here's how this could be done by using JavaScript:

function addValidationIcons () {
 var a = document.getElementsByTagName("a");
 for (var i=0; i<a.length; i++) {
  var aHref = a[i].getAttribute("href");
  if (aHref.indexOf("http://validator.w3.org/") != -1) {
   a[i].innerHTML = '<img src="../../img/valid-xhtml.png" alt="eXtensible HyperText Markup Language" />';
  } 
  
  else if (aHref.indexOf("http://jigsaw.w3.org/") != -1) {
   a[i].innerHTML = '<img src="../../img/valid-css.png" alt="Cascading Style Sheet" />';
  }
 }
}

Basically, we loop through each link on the page and if its href attribute contains either the string http://validator.w3.org/ or the string http://jigsaw.w3.org/, we change its content via the innerHTML property by setting it to an image that contains our icon. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.