It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.
As of jQuery 1.12/2.2, this behavior is changed to improve the support for XML documents, including SVG. Starting from this version, the
class
attribute
is used instead. So,
.addClass()
can be used on XML or SVG documents.
More than one class may be added at a time, separated by a space, to the set of matched elements, like so:
Add the class "selected" to the matched elements.
<title>addClass demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
$( "p" ).last().addClass( "selected" );
<title>addClass demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
$( "p" ).last().addClass( "selected highlight" );
<title>addClass demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
$( "p" ).last().addClass( [ "selected", "highlight" ] );
<title>addClass demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<div>This div should be white</div>
<div class="red">This div will be green because it now has the "green" and "red" classes.
It would be red if the addClass function failed.</div>
<div>This div should be white</div>
<p>There are zero green divs</p>
$( "div" ).addClass(function( index, currentClass ) {
if ( currentClass === "red" ) {
$( "p" ).text( "There is one green div" );
Web hosting by Digital Ocean
|
CDN by Fastly
|
Powered by WordPress