Headline replacement via Javascript

Update: As mentioned in the comments to the article on alistapart, this technique still has some flaws, the first changes here are that the variables get declared locally and that the nested looping of headlines and images got a break once the text corresponding to the image was found.

Download the version 1.1

As Todd Fahrner's Image replacement technique proved to be dependent on a screen reader working the wrong way, Peter Paul Koch mentioned on the CSS-D that Javascript might be the more logical way to achieve graphical headlines that are accessible.

I pondered that thought a bit, and came up with this solution:

/*
	firdom() version 1.1 (24.11.2003)
	written by Chris Heilmann (http://www.onlinetools.org)
*/
function firdom(){
	if(document.getElementsByTagName && document.createElement){
		for (var l=1;l<=6;l++){
			var h1s=document.getElementsByTagName('h'+l);
			scanandreplace(h1s,'h'+l);
		}
	}
}
function scanandreplace(h1s,tag){
	for(var i=0;i<h1s.length;i++){
		for(var f=0;f<replaceImages.length;f++){
			var chunks=replaceImages[f].split('|');
			var thish1=document.getElementsByTagName(tag)[i];
			if(thish1.firstChild.nodeValue==chunks[0]){
				var newImg=document.createElement('img');			
				newImg.setAttribute('alt',chunks[0])
				newImg.setAttribute('src',chunks[1])
				// or newImg.src=chunks[1];
				thish1.replaceChild(newImg,thish1.firstChild)
				break;
			}
		}
	}
}
window.onload=firdom;

All you need to do to implement this technique is to define your images in an array and call the main function in the head of your web site.

Let's say you want to replace the headlines "About us", "History" and "Contact Us" with the images "about.gif", "history.gif" and "contact.gif"

All you'd need to put in the head section of the page is

<script type="text/javascript">
<!--
replaceImages = new Array(
'About us|about.gif',
'History|history.gif',
'Contact Us|contact.gif');
//-->
</script>
<script type="text/javascript" src="firdom.js"></script>

And firdom will replace these headlines with the fitting graphics. It does not matter which level (1 to 6) the headline is, and the image will have the original wording of the headline as an alt attribute.

If you have more than one script on your site you need to execute when the page loads, delete the line

window.onload=firdom;

and either call firdom in your initiating function, or in the <body> tag of your page via the onload attribute.