From the front lines

Posted by: | Uncategorized | 17.04.2007

Just quickly, whilst working on something today (sorry Top Secret, can’t tell you – i’d have to send the Ninjas round) I ran into the need to add some spans to <a> tags. But in such a way that it was automated. And sometimes different


// Justins awesome access <a> thingee...
var initialText
var firstCharacter
var remainingWord
function startMe() {
	var m = document.getElementsByTagName('a'), i;
	for (i = 0; i < m.length; ++i) {
		if (m[i].className == 'button') {
			initialText = m[i].innerHTML;

			m[i].innerHTML = '<span> </span>' + initialText;
		}
		if (m[i].className == 'button access') {
			initialText = m[i].innerHTML;

			firstCharacter = initialText.charAt(0);
			remainingWord = initialText.split(firstCharacter)[1];

			m[i].innerHTML = '<span>' + firstCharacter + '</span>' + remainingWord;
		}
	}
}

Basically it loops through the <a> tags on your page and inserts a span before the existing text, or if it’s got an additional class of ?access? then it wraps the first letter within the span as well.

It can be initialized in one of two ways, either:


addLoadEvent(startMe);

or in the onLoad of the body tag.

Leave a Reply