Saturday, September 24, 2011

CSS Class Selector examples in JQuery

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.

And it appears in browser as under

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:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape