1

since jQuery 1.4 removeClass(); now takes a function as argument.

My <body> tag has a few classes added to it, for example:

<body class="heading-helvetica para-georgia pattern-flowers">

I wish to be able to replace the classnames, and I believe the function in removeClass() can help me, but I don't really understand the documentation on the jQuery site nor am I any good with Regex.

How can I replace for example heading-helvetica with heading-myriad or para-georgia with para-times and so on?

I had previously used something like this, which works only if the class name it is trying to replace is the first in the list of class names:

$('#headings li').click(function(){
    var this_class = $(this).attr('id');
    $('body[class|="heading"]').removeClass();
    $('body').addClass(this_class);
});
Joe W
  • 998
  • 6
  • 16
  • 36
  • `$('something').removeClass('heading-helvetica').addClass('heading-myriad');`. Is there some reason this won't work for you? – rossipedia Nov 07 '11 at 18:03

2 Answers2

2

You will need to get the list of classes from the body tag and iterate / parse them.

See this article for how to get the classes.

Get class list for element with jQuery

You will have to figure out a list of classes to add and a list of classes to remove. Using a function as the parameter of the removeClass method isn't really necessary. Since you also need to add classes, it probably is the wrong way to go.

Community
  • 1
  • 1
BNL
  • 7,085
  • 4
  • 27
  • 32
0

If you want to handle them all, you can use .attr() instead. Example:

var prev = $("body").attr('class'); $("body").attr('class', prev.replace('helvetica', 'myriad'));

That's pretty broad though, depending on what you're doing you may be better off with removeClass() and addClass().

jeffff
  • 1,309
  • 1
  • 7
  • 23