0

I'm working inside a templated system where i can implement code, but i can't modified the core of the file. My layer are stacked like this:

<div class="layer1">
    <div class="layer2">
        <div class=" layer3">
            <div class="layer4">
            </div>
        </div>
    </div>
</div>
<div class="layer1">
    <div class="layer2">
        <div class=" layer3">
            <div class="layer4">
            </div>
        </div>
    </div>
</div>
<div class="layer1">
    <div class="layer2">
        <div class=" layer3">
            <div class="layer4">
            </div>
        </div>
    </div>
</div>

As you can see, my class all have the same name (layer1, layer2, etc...). I want to know if there's a way by using Javascript, Jquery or any other online client side library to modify the CSS class name so, for example, the first layer1 become level1 and the following layer1 become level 2?

Thank for your answer!

3 Answers3

0

Many different ways to do this:

Solution 1:

Use addClass() and removeClass()

$(".layer1").removeClass('old_class').addClass('new_class');

Replace old_class with your older class and new_class with your new class

Solution 2:

If you are able to get the element by ID

You can set the class by using .attr()

$("#id").attr('class', 'new_class');
imbondbaby
  • 6,351
  • 3
  • 21
  • 54
0

As other people already said, jQuery actually does what you want.

As long as you don't know the number of “layers” you have, you better find all elements by classname substring:

$('*[class^="layer"]')

Then you can get the list of the element classes and change old names to new ones.

Community
  • 1
  • 1
Vadim Pushtaev
  • 2,332
  • 18
  • 32
0

an all around solution working with className :

 var elem=document.querySelectorAll('[class^="layer"]') ;

 for(i in elem){    
 x = elem[i].className;
 var y=x.replace("layer" , "level");
 elem[i].className=y||x; 
 }
maioman
  • 18,154
  • 4
  • 36
  • 42