In this post we will understand more about CSS Class Selector in JQuery. CSS Class selector is selecting CSS Class in JQuery.
Continue with our earlier example of JQuery Selector
This time, i have defined two css classes in css style file for paragraph tag. i.e. para1 and para2. This two css class have few font family and size change.
My HTML looks something as below image.
Now let see, how class selector works in JQuery.
Example 1: Let select paragraph tag with css class as "para1" in our page and change its text background to yellow color. Also select paragraph tag with css class as "para2" in our page and change its text background to lime color.
Please add below script at the end of the page.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(".para1").css("background-color", "Yellow");
$(".para2").css("background-color", "lime");
});
</script>
It will result in following output on browser screen.
Please note, that class selector should always start with "." (dot). Selector will not be able to select class element if defined without "."
Example: Incorrect way of declaration - Class element without "." (dot)
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("para1").css("background-color", "Yellow");
$("para2").css("background-color", "lime");
});
</script>
Example: Correct way of declaration - Class element with "." (dot)
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(".para1").css("background-color", "Yellow");
$(".para2").css("background-color", "lime");
});
</script>
Example 2: To be more specific in above example that only paragraph tag which has class name as para1, should only assign background color as yellow, you should explicitly mention "p.para1" rather than ".para1"
Please add below script at the end of the page.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("p.para1").css("background-color", "Yellow");
});
</script>
It will result in following output on browser screen.
No comments:
Post a Comment