I can’t seem to use the function changeTab(num) to change the ID of a li element from number to selected, and to revert selected tab’s ID to its default number. It only works one or two times and then stops. My goal is to mimic the change of selected and unselected tab, like for example in Chrome tabs.
<ul id="nav">
<li onClick="changeTab(1);" id="1"><a href="#">Nav 1</a></li>
<li onClick="changeTab(2);" id="2"><a href="#">Nav 2</a></li>
<li onClick="changeTab(3);" id="selected"><a href="#">Nav 3</a></li>
<li onClick="changeTab(4);" id="4"><a href="#">Nav 4</a></li>
</ul>
My JavaScript code is:
function changeTab(num){
switch(num){
case 1:
document.getElementById("selected").id = "1";
break;
case 2:
document.getElementById("selected").id = "2";
break;
case 3:
document.getElementById("selected").id = "3";
break;
case 4:
document.getElementById("selected").id = "4";
break;
default:
document.getElementById("selected").color = "";
}
//
document.getElementById(num).id = "selected";
EDIT as WTK suggested (as a comment in your question above) for this to be valid HTML, id values must start with a letter and not a number… I’ve updated my answer to be valid HTML by prepending the id with
nav-…Using the
thisvariable within the onclick handler will get the element being clicked… Then you can use the following function as the handler…There are other, possibly better, ways to do this. This should solve the problem though, if you wanted to delve deeper I would recommend the book Pro JavaScript Design Patterns.