jQuery removeClass
A pair of the removeClass and addClass essentially replace a class. If you checked the last example in the
previous post , you may have noticed the issue with dynamically changing the class associated with selected element.
Here is the example that shows the usage of the removeClass example.
<! DOCTYPE html>
<!-- Referencedesigner.com Example -->
< html>
< head>
< style>
.highlightyellow { background: yellow; }
.highlightpink { background: pink; }
</ style>
< script src= "http://code.jquery.com/jquery-latest.js" ></ script>
</ head>
< body>
< p> Referencedesigner.com removeClass example</ p>
< p> Second Paragraph</ p>
< p> This last line will get highlighted when button "Highlight last line" is pressed </ p>
< button id = "button1" > Highlight Last Line with yellow</ button>
< button id = "button2" > Highlight Last Line with Pink</ button>
< script>
$( "button#button1" ) .click ( function ( ) {
$( "p:last" ) .removeClass ( "highlightpink" ) ;
$( "p:last" ) .addClass ( "highlightyellow" ) ;
} ) ;
$( "button#button2" ) .click ( function ( ) {
$( "p:last" ) .removeClass ( "highlightyellow" ) ;
$( "p:last" ) .addClass ( "highlightpink" ) ;
} ) ;
</ script>
</ body>
</ html>
You may like to try this example
here .
See how you can now dynamically change the class.
Notice that the two statements
$("p:last").removeClass("highlightpink");
$("p:last").addClass("highlightyellow");
can be combined to a single line
$("p:last").removeClass("highlightpink").addClass("highlightyellow");