Skip to content

Instantly share code, notes, and snippets.

@Scordavis
Last active April 29, 2017 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Scordavis/82011461d63aecb189b2d510f999bac0 to your computer and use it in GitHub Desktop.
Save Scordavis/82011461d63aecb189b2d510f999bac0 to your computer and use it in GitHub Desktop.
jquerry
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:
This method is often used with .removeClass() to switch elements' classes from one to another, like so:
Here, the myClass and noClass classes are removed from all paragraphs, while yourClass is added.
As of jQuery 1.4, the .addClass() method's argument can receive a function.
Given an unordered list with two <li> elements, this example adds the class "item-0" to the first <li> and "item-1" to the second.
Examples:
Add the class "selected" to the matched elements.
$( "p" ).addClass( "myClass yourClass" );
$( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" );
$( "ul li" ).addClass(function( index ) {
return "item-" + index;
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>addClass demo</title>
<style>
p {
margin: 8px;
font-size: 16px;
}
.selected {
color: blue;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
<script>
$( "p" ).last().addClass( "selected" );
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment