Search code examples
javascriptclasstabsurlvariables

JavaScript Make Tabs


So, I am trying to make a "tabs menu", like this: http://flowplayer.org/tools/tabs/index.html (but i dont want to use this.) So, I tried to use url variables to set the active menu item. Code:

onload=function(){
    //Check if editPage is set
    if (gup("editPage")) {
        gupname = gup("editPage");
        var x = "contentEditListItem"+gupname; 
        var y = document.getElementsByClassName(x);
        y.className = "contentEditListItemActive";
    } 
}
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

The gup function works well, I get the wanted classname ("contentEditListItem"+gupname). Why it is staying unchanged?


Solution

  • getElementsByClassName returns a NodeList (kind of Array), so setting a property on that is not affecting the elements that it contains, but only the NodeList itself, which has no effect.

    You could set the class name of the first element, for example, like this:

    y[0].className = "contentEditListItemActive";
    

    Or, if you want all elements have their class name changed, you could iterate over the NodeList:

    for(var i = 0; i < y.length; i++) {
        y[i].className = "contentEditListItemActive";
    }