0

I would like to replace the class's suffix while preserving its prefix

DEMO: http://jsbin.com/vozufura/4/edit

The desired code should make all the div black. So that:

  • class= menu-456 AND menu-789 should be replaced and become menu-123
  • All the div should be black as a result

HTML:

  <div class="menu-123">black</div>
  <div class="menu-456">green</div>
  <div class="menu-789" >red</div>

CSS:

.menu-123 {
  background: black;
}

.menu-456 {
background: green;
}

.menu-789 {
  background: red;
}

Javascript (Jquery):

 /* I am not looking for javascript like removeClass nor addClass, 
nor do i want to change the background. 
I wanted to know if it is possible to REPLACE the suffix of a class*/
Wiley Ng
  • 307
  • 3
  • 14
  • I'd recommend taking a look at Codecademy to help you start off with the JavaScript: http://www.codecademy.com/en/tracks/javascript . – Casey Falk Aug 13 '14 at 13:02
  • Different ways of changing the bg colour to black. You can just set the bg colour in js and it will work. – Huangism Aug 13 '14 at 13:08
  • I understand, the "change to background" is just a demo. I want to replace the suffix of the class in a more complex coding that is not display here in demo. – Wiley Ng Aug 13 '14 at 13:58

3 Answers3

0

Use a combination of removeClass() and addClass() functions provided by jQuery, like this:

$(document).ready(function(){
    $(".menu-456,.menu-789").removeClass("menu-456 menu-789").addClass("menu-123");
});

This code runs when the DOM is loaded and what it does is as follows:

  1. It selects all elements with either class menu-456 or menu-789.
  2. It removes classes menu-456 and menu-789 from those elements.
  3. It gives the elements the class menu-123.

FIDDLE

ZiNNED
  • 2,620
  • 20
  • 31
0

your jquery JS:

 $(document).ready(function () {
  $('[class^=menu-]').not('.menu-123').removeClass().addClass('menu-123');
});

you can you addClass and removeClass

DEMO

Amit Kumar
  • 5,888
  • 11
  • 47
  • 85
0

Changing and messing with classes is easy with jQuery. Take a look at .addClass .removeClass.
You can use the Attribute Contains Selector or Attribute Contains Prefix Selector to be more general and effective in your code.

For example, if you want menu-123 to be the only new class on the element:

$("div[class|='menu']").attr('class', 'menu-123');

or, if you want to get clever:

$("div[class|='menu']").attr('class', function(i, c){
  return c.replace(/(^|\s)menu-\S+/g, 'menu-123');
});

thanks to this answer.

Community
  • 1
  • 1
Alon Dahari
  • 1,138
  • 1
  • 9
  • 27