JQuery

How to replace the css class using jQuery?

How to replace the css class using jQuery?, someone asked me to explain?

In this tutorial I will show you how to replace the class using jQuery.  When the user click the grid view it will be listed in grid view, if the user click the list view the content will be listing.

 

I here used jQuery attribute method function for changing from one css class to another css class.

 

The following example working perfectly, it will work dynamically on button click. You can also customize using the following concept and apply to change the css using jQuery. You should refer the latest version of the jQuery.

<script type="text/javascript">
    function changetoGrid() {
        $(".sp-list").attr('class', 'col-sm-12 sp-list');
    }
    function changetoList() {
        $(".sp-list").attr('class', 'col-sm-6 sp-list');
    }
</script>
 
<input type="radio" name="view-filter" id="list-view" onclick="changetoList();"  class="list-view-radio view-radio" checked><label for="list-view" style="float:right"><i class="fa fa-list-ul"></i> List View</label>
 
            <input type="radio" name="view-filter" id="grid-view" onclick="changetoGrid();" class="grid-view-radio view-radio"><label for="grid-view" style="float:right"><i class="fa fa-th"></i> Grid View</label>
 
<article class="block-item">
                    <img src="http://www.placecage.com/g/300/300">
                    <div class="entry-content">
                        <h1 class="entry-title">Entry One</h1>
                        <div class="col-sm-6 sp-list">
                            <div class="text">
                                <h6 class="cust-head"><span class="key">Front Camera: </span> 1.2MP</h6>
                                <h6 class="cust-head">
                                    <span class="key">Rear : </span>  8MP
                                </h6>
                            </div>
                        </div>
                        <div class="col-sm-6 sp-list">
                           <!-- Search form -->
                            <div class="text">
                                <h6 class="cust-head"><span class="key">Front Camera: </span> 1.2MP</h6>
                                <h6 class="cust-head">
                                    <span class="key">Rear : </span>  8MP
                                </h6>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <p>
                            This is my short description text for this item.
                            Product description... Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
                        </p>
                    </div>
                </article>

Output:

replace the css class using jQuery

Post your comments / questions