A JS-Fix for ie6 inabillity to style ancestors of hovered links

I got fed up with Internet Explorer 6 inability to apply CSS rules to ancestors of hovering links, e.g. this:

a:hover span{
   background-color: yellow;
}

won’t work in Internet Explorer 6.

Apparently IE7.js doesn’t fix that issue (there is already a bug ticket about that, though) so I wrote this little helper function in javascript:

function addhover(){
  var link = document.getElementsByTagName('a');
  var linklength = link.length;
  for(i=0; i < linklength; i++) {
    link[i].onmouseover = function() {
      this.className += this.className ? ' hover' : 'hover';
    }
    link[i].onmouseout = function() {
      var rep = this.className.match(' '+'hover') ? ' '+'hover' : 'hover';
      this.className=this.className.replace(rep,'');
    }
  }
}
addhover();

or, if you prefer jquery:

$('a').mouseover(
  function(){
    $(this).addClass('hover');
  }
).mouseout(
  function(){
    $(this).removeClass('hover');
  }
);

Of course, you’ll have to adjust slightly your CSS for that:

a.hover span,
a:hover span{
   background-color: yellow;
}

which is a reasonable trade off, I think.

I suggest you take this script in a single js-file and include it in a conditional comment just before the body closes, like this:


	


or, if you want, you can call the function from a non-standard event handler:

if (window.attachEvent) window.attachEvent("onload", addhover);

The function itself is (due to its simplicity) quite fast: it takes about 3s for 10000 Links (try the benchmark), which is way more than any given document should have.

Note: This has probably been done a million times out on the internet – I just couldn’t find something quickly enough.