How to use addclass() method with function in JQuery

In this article, I will explain use of addclass() method with function in JQuery.
  • 2322

JQuery CSS addclass() Method with Function

  • A function returning one or more space-separated class names to be added to the existing class.

  • In function, this refers to the current element in the set.

Syntax

$(selector).addClass(function(index,oldclass))
  • index - This is the optional in function. Index received the index position of the selector.

  • oldclass - This is the optional in function. oldclass received the old class value of the selector.

Example

The following example shows how to addclass() method using function in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function ()

    {

        $("button").click(function ()

         {

             $('p').addClass(function (n)

             {

                return 'class_' + n;

            });

        });

    });

</script>

<style type="text/css">

.class_0

{

color:Lime;

font-style:italic;

background-color:Teal;

}

.class_1

{

color:red;

font-style:oblique;

background-color:Yellow;

}

</style>

</head>

<body>

<h1>Add Class Using a Function</h1>

<p>First paragraph.</p>

<p>Second paragraph.</p>

<button style="border-bottom-style:solid">Add classes to p elements</button>

</body>

</html>

 

Output


addclass function.jpg

 Further Readings

You may also want to read these related articles here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.