Articles → JQUERY → Addclass And Removeclass In Jquery
Addclass And Removeclass In Jquery
Prerequisite
- Hands on experience in jquery.
- Hands on experience in creating html page.
- Hands on experience in using css.
Addclass
$("<element_id>").addClass("<class_Name>");
Removeclass
$("<element_id>").removeClass("<class_Name>");
Attr
$("<element_id>").attr("<attribute_Name>");
$("div#testDiv").attr("class")
Sample Application
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>addClass and removeClass demo</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(
function() {
$("input#btnBold").click(
function() {
if ($("div#sampleDiv").attr("class") != undefined) {
$("div#sampleDiv").removeClass("applyItalicClass");
}
$("div#sampleDiv").addClass("applyBoldClass");
}
);
$("input#btnItalic").click(
function() {
if ($("div#sampleDiv").attr("class") != undefined) {
$("div#sampleDiv").removeClass("applyBoldClass");
}
$("div#sampleDiv").addClass("applyItalicClass");
}
);
}
);
</script>
<style type="text/css">
.applyBoldClass
{
font-weight: bold;
}
.applyItalicClass
{
font-style: italic;
}
</style>
</head>
<body>
<div id="sampleDiv">Sample Text</div>
<input type="button" value="bold" id="btnBold" />
<input type="button" value="Italic" id="btnItalic" />
</body>
</html>