jqueryexample.com jQuery add / remove class example - jqueryexample.com

jQuery add / remove class example by jqueryexample

With jQuery we can addClass() and removeClass() to add or remove CSS class dynamically.
Example1:
For handling the adding/removal of the selected class first we defined two classes in CSS
<style>
.even { background: #fff; border: 1px solid #ccc; }
.odd { background: #ccc; } </style>

<html>
<head>
<title>the title</title>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("ul li:even").addClass("even");
$("ul li:odd").addClass("odd"); });
$("ul.myList").removeClass("myList"); });
</script>
</head>
<body>
<ul class="myList">
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</body>
</html>

Example2:
In CSS define one class active and on over/mouse out of list we will add/remove class.
CSS: .active {background: #ccc;}

$("ul.myList li").hover(
function() {
$(this).addClass('active');
},
function() {
$(this).removeClass('active');
}
);

$(“ul.myList li:first”).addClass(“first”);

Did you like this? Share it:

Discussion

No comments yet, be the first.

Leave a Comment