.addClass()
In this chapter you will learn:
Syntax and Description
.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
.addClass() method adds 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.
The following code add myClass yourClass
for paragraph 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();
});
Its return value is the jQuery object, for chaining purposes.
Add style for the last paragraph
The following code gets last paragraph and adds class.
<html><!-- j a v a 2 s . com-->
<head>
<script src="http://java2s.com/style/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>
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for .after() method
- How to insert text node after paragraph
- How to insert hard coded HTML element
- How to insert a selected node from the same HTML document