.addClass()
Syntax
.addClass(className)
- className: One or more class names to be added to the class attribute of each matched element
.addClass(function)
- function: A function returning one or more space-separated class names to be added
Return value
The jQuery object, for chaining purposes.
Description
Add one or more classes to each element in the set of matched elements.
More than one class may be added at a time, separated by a space, to the set of matched elements.
$('p').addClass('myClass yourClass');
The .addClass() method allows us to set the class name by passing in a function.
$('ul li:last').addClass(function() {
return 'item-' + $(this).index();
});
If has class
<html>
<head>
<script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").append($("p:first").hasClass("selected").toString());
});
</script>
</head>
<body>
<body>
<p>A</p>
<div></div>
</body>
</html>
<html>
<head>
<script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p:last").addClass("selected highlight");
alert($("p:last").hasClass("selected").toString());
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<body>
<p>A</p>
<p>B</p>
<p>C</p>
</body>
</html>
Get last paragraph and add class
<html>
<head>
<script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p:last").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<body>
<p>A</p>
<p>B</p>
<p>C</p>
</body>
</html>
Home
JavaScript Book
jQuery
JavaScript Book
jQuery
DOM:
- jQuery DOM
- $("html tags"):generate code with the jQuery wrapper function.
- .add()
- .addClass()
- .after()
- .andSelf()
- .append()
- .appendTo()
- .attr()
- .before()
- .children()
- .clone()
- .closest()
- .contents()
- .css()
- .detach()
- .filter()
- .first()
- .get()
- .has()
- .hasClass()
- .height()
- .html()
- .index()
- .innerHeight()
- .innerWidth()
- .insertAfter()
- .insertBefore()
- .is()
- .last()
- .map()
- .next()
- .nextAll()
- .nextUntil()
- .not()
- .offset()
- .offsetParent()
- .outerHeight()
- .outerWidth()
- .parent()
- .parents()
- .parentsUntil()
- .position()
- .prepend()
- .prependTo()
- .prev()
- .prevAll()
- .prevUntil()
- .remove()
- .removeClass()
- .removeAttr()
- .replaceAll()
- .replaceWith()
- .siblings()
- .scrollLeft()
- .scrollTop()
- .slice()
- .text()
- .toArray()
- .toggleClass()
- .unwrap()
- .val()
- .wrap()
- .wrapAll()
- .wrapInner()
- .width()