Is there a better way than the implementation I have now? I’m concerned that the way I’ve done it is a little hackish and am wondering if there’s a more elegant solution.
I want to change the “selected” element on the page by applying a CSS class to it, and remove the one that is currently selected. The code I have for changing the element’s class:
function changeClass(element) {
document.getElementById("nav").getElementsByClassName("selected")[0].className = "";
element.className = "selected";
}
And the corresponding elements:
<div id="nav">
<ul>
<li><a href="#" onclick="changeClass(this)" class="selected">Main</a></li>
<li><a href="#" onclick="changeClass(this)">Downloads</a></li>
<li><a href="#" onclick="changeClass(this)">News</a></li>
<li><a href="#" onclick="changeClass(this)">Forums</a></li>
<li><a href="#" onclick="changeClass(this)">Proposals</a></li>
</ul>
</div>
Again, this seems a little hacky. Is there a better way of accomplishing what I’m trying to do?
Using the getElementByClassName isn’t too recommended, because currently there are browser that don’t fully support this functionnality (mainly IE). This is probably something that would work better on all browser :