SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Feb 2005
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Change class name

    Hi,

    So i like to change class name from a html page with javascript.

    I found this code that does change the class name
    Code:
    loopCSSChange = function (el, class, newclass)
    {
       for (var x=0;x<el.childNodes.length;x++)
      {
            loopCSSChange(el.childNodes[x], class, newclass);
    
      }
    
      if (el.className==class) el.className=newclass;
    
    }
    
    loopCSSChange(document, "oldclass", "newclass");
    But the problem is that the page has multiple classes with the same name
    Code:
    <td class="oldclass">...</td>
    <td class="oldclass">...</td>
    <td class="oldclass">...</td>
    Is it possible to change the first class with newclass1, the second one with newclass2, etc...
    So that it would look like this:
    Code:
    <td class="newclass1">...</td>
    <td class="newclass2">...</td>
    <td class="newclass3">...</td>
    grtz

  2. #2
    Non-Member Kalon's Avatar
    Join Date
    Aug 2010
    Location
    At my computer
    Posts
    2,012
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    one option is to use a getElementByClassName function and then loop through the returned element objects and change their className to whatever you need.

    Code:
     
    function getElementsByClassName(oElm, strTagName, strClassName)  {
        var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        strClassName = strClassName.replace(/\-/g, "\\-");
        var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
        var oElement;
        for(var i=0; i<arrElements.length; i++)
        {
            oElement = arrElements[i];
            if(oRegExp.test(oElement.className))
            {
                arrReturnElements.push(oElement);
            }
        }
        return (arrReturnElements)
    }
     
    //example usage
     
    var divObjs = getElementsByClassName(document,'div','myClass');


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •