0 Comments

You can add a CSS class to a HTML element, only when this class is not present on the HTML element, by using the jQuery function .toggleClass and using the switch parameter:

If your HTML page contains a div like:

<div id="title">
...
</div>

Adding the JavaScript code:

$(document).ready(function ()
{
    // The CSS class "titleStyling", will now be added, because it is does not exist on the title yet.
    $("#title").toggleClass("titleStyling", true);

    // Subsequent calls will not add extra classes, where the jQuery .addClass will.
    $("#title").toggleClass("titleStyling", true);

    // Subsequent calls will not add extra classes, where the jQuery .addClass will.
    $("#title").toggleClass("titleStyling", true);
});

Will result in

<div id="title" class="titleStyling">
...          
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.