<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Options</title>
<style type="text/css">
h1.clicked { background: red; }
</style>
</head>
<body>
<h1>Click here a few times</h1>
<script type="text/javascript">
var toggle = function(elem , className ) {
// remove allows for multiple classNames and strips the appropriate spaces
// e.g. removing class2 from 'class1 class2 class3'
var remove = new RegExp ('\\s'+className+'|'+className+'\\s|'+className),
match = new RegExp ('\\b'+className+'\\b'),
currClass = elem.className;
// does the element already have the class
if (match.test(currClass)) {
elem.className = currClass.replace(remove, ''); // then remove class
} else {
elem.className += ' ' + className; // else add class
}
}
// elementsByTagName returns an array.
// Adding the index[0] selects the first one.
var headElem = document.getElementsByTagName('h1')[0];
headElem.onclick = function(){ toggle(headElem, 'clicked'); }; // clicked is the class name. See the CSS.
</script>
</body>
</html>
Bookmarks