Question

I created a page to play around with the 960 Grid System, learn about div placement. There are up to four divs on the page. When a new grid size, pull or push value is selected from a dropdown, I need to remove the current class, i.e. grid_8, pull_5 or push_4, and add the newly selected class.

function alter_grid1(new_class_name){

   var old = document.getElementById('grid1');
   var classes = old.className.split(' ');
   var old_class_name = 'cessna';
   $.each(classes, function(){

        if(old_class_name == 'cessna' || old_class_name == null){
          old_class_name = this.match('/grid_1|grid_2|grid_3|grid_4|grid_5|grid_6|grid_7|grid_8|grid_9|grid_10|grid_11|grid_12|grid_13|grid_14|grid_15|grid_16|grid_17/');
       }
   });
   $(old).removeClass('grid_1 grid_2 grid_3 grid_4 grid_5 grid_6 grid_7 grid_8 grid_9 grid_10 grid_11 grid_12 grid_13 grid_14 grid_15 grid_16').addClass(new_class_name);
   console.log('Old grid1 class name is ' + old_class_name + ' and New grid1 class name is ' + new_class_name);
}

I can use addClass(new_class_name); without any trouble.

I can use use removeClass('grid_8'); without any trouble (grid_8 being the actual class name)

When I use removeClass(old_class_name); it just doesn't work. No error message, nothing in firebug, just doesn't work.

Since I don't know what the previous value will be, I have to remove any possible class that could be there

 $(old).removeClass('grid_1 grid_2 grid_3 grid_4 grid_5 grid_6 grid_7 grid_8 grid_9 grid_10 grid_11 grid_12 grid_13 grid_14 grid_15 grid_16').addClass(new_class_name);

That's the only way I can get it to work. Sure it works, but seems like I'm either missing something or doing something wrong. You can see what I'm trying to do here if it would help. I just don't see how I can add a class using a var, but not remove one the same way.

Was it helpful?

Solution

Seems your regex is wrong. Use either a string without the slashes or just the slashes.

old_class_name = this.match(/grid_1|grid_2|grid_3|grid_4|grid_5|grid_6|grid_7|grid_8|grid_9|grid_10|grid_11|grid_12|grid_13|grid_14|grid_15|grid_16|grid_17/);

or maybe even

old_class_name = this.match(/grid_[0-9]+/);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top