Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace special class with another in jquery?

E.g:

<li class="dataItem ready igto" status="ready">I will change status to waiting</li>

and then ,I just want to change the ready class to waiting.THe normal way is to removing the class ready and adding new class!

and another situation is how to replace multi class at once!? E.g:

<!-- replace done wainting error to ready -->
<li class="dataItem done igto" status="ready">I will change status to ready</li>
<li class="dataItem waiting igto" status="ready">I will change status to ready</li>
<li class="dataItem error igto" status="ready">I will change status to ready</li>

to :

<li class="dataItem ready igto" status="ready">I will change status to waiting</li>

Thank you very much!!

like image 745
qinHaiXiang Avatar asked Feb 15 '11 02:02

qinHaiXiang


People also ask

How can I replace one class with another in jQuery?

To replace all existing classes with another class, we can use . attr( "class", "newClass" ) instead. As of jQuery 1.4, the . removeClass() method allows us to indicate the class to be removed by passing in a function.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

Which method is used to replace with the keyword jQuery?

jQuery replaceWith() Method The replaceWith() method replaces selected elements with new content.


1 Answers

You can use $.toggleClass() to achieve this.

$("p").click(function(){
  // Replace 'done' with 'waiting' or 'waiting' with 'done'
  $(this).toggleClass("done waiting");   
});

Example: http://jsfiddle.net/wH9x3/

like image 127
Sampson Avatar answered Sep 22 '22 01:09

Sampson