6B. CSS - addClass() / removeClass()
In this chapter, we're going to see how we can add CSS attributes via jQuery.
Here is our html file (j6_css_manipulation2.html):
<html> <head> <title>CSS Manipulation via jQuery</title> <meta charset=utf-8" /> <style type="text/css"> .smaller {font-size: 15px;} .emp {text-decoration: underline; color: green;} </style> </head> <body> <h1>1st heading</h1> <h1>2nd heading</h1> <h1>3rd heading</h1> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js""></script> <script type="text/javascript" src="jQuery_css_manipulation_remove.js"></script> </body> </html>
Note that in the style tag, we had .emp and smallerattribute which we haven't used. Now, we want to add those attributes to our js file. How we do it?
We can use addClass() method:
$(document).ready(function() { $("h1").mouseenter(function() { $(this).addClass("emp smaller"); }); });
The playback below shows what are the effects:
To show how to remove class, we may want to add the two class (smaller, emp) to 2nd heading of our html(j6_css_manipulation_remove.html)(:
<html> <head> <title>CSS Manipulation via jQuery</title> <meta charset=utf-8" /> <style type="text/css"> .smaller {font-size: 15px;} .emp {text-decoration: underline; color: green;} </style> </head> <body> <h1 class="smaller emp">1st heading</h1> <h1 class="smaller emp">2nd heading</h1> <h1>3rd heading</h1> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js""></script> <script type="text/javascript" src="jQuery_css_manipulation_remove.js"></script> </body> </html>
To remove class from a selector, we use remove() as shown in the js file below:
$(document).ready(function() { $("h1").mouseenter(function() { $(this).removeClass(); }); });
We can remove a specific class by providing the name as a parameter to the remove() method:
$(this).removeClass("smaller");
There are more methods such as toggleClass() etc.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization