X

LATEST #JQUERY NEWS

Useful jQuery Code Snippets for Handling CSS


If you’re not already familiar with code snippets, they are handy time savers! Essentially, the feature you want to implement is already created by someone else and is available for reuse. Handling CSS with jQuery can sometimes be tricky and time consuming. This post provides a list of useful jQuery code snippets for handling CSS related tasks with ease. These snippets are useful for adding, removing CSS classes, playing with inline CSS style, loading CSS dynamically and several other tasks. Check it out!

  1. Add a CSS Class to any element

The following code will add a CSS class to the jQuery matched selector: addClass(). It is a jQuery method that allows you to add CSS class(es) to a selector. It will not replace the existing CSS class (if applied), but will instead add the CSS class. This will add the class attribute to the HTML element.

$(document).ready(function(){
  $("selector").addClass("myClass");
});

If you want to add multiple CSS classes then you can separate them using a simple space between:

$("selector").addClass('myClass1 myClass2');
  1. Remove CSS Class from any element

Similar to addClass(), jQuery also provides removeClass() which is a snippet which allows you to remove any assigned CSS class. The following code will remove the myClass from the matching jQuery selector:

$(document).ready(function(){
   $("selector").removeClass("myClass");
})
  1. Remove All CSS Classes

If you wish to remove all CSS classes from the element, then use removeClass(), with no parameters. It looks like this:

$(document).ready(function(){
   $("selector").removeClass();
})
  1. Check if the element has a particular CSS class assigned

The following code will check if the matched jQuery selector has myClass assigned to it. If it does, then it will return true. Otherwise, it will return false. jQuery provides the .hasClass() snippet to check if the CSS class is applied to the element or not. Like this:

$(document).ready(function(){
   var bResult = $("selector").hasClass("myClass");
})
  1. Toggle CSS class

If you wish to add or remove a CSS class, the toggleClass() snippet can be used. This code toggles between adding/removing classes from the matching jQuery elements:

$(document).ready(function(){
   $("selector").toggleClass("cssclass");
})
  1. Assign an inline CSS style to the element

Sometimes you will need to apply inline styles to the element, instead of applying CSS class. For this, jQuery provides the .css() code which allows you to set one or more style properties for the selected elements:

$(document).ready(function(){
  $("div").css("background-color", "red");
})

The above code will set a red background color to all div elements present on the page. The .css() snippet adds inline style attributes to HTML elements. You can also use this method to get the style value, like this:

$(document).ready(function(){
  var bgColor = $("div").css("background-color");
})

The above code will return the value of a specified CSS property.

  1. Remove inline styles from the element

The following code will remove inline style attributes from all div elements present on the page, using the removeAttr() code:

$(document).ready(function(){
   $("div").removeAttr("style");
})
  1. Remove all inline styles from the HTML page

If you wish to remove all of the inline style present on the HTML page, the jQuery code featured below can be used. This page selects all of the elements on the page that have style attributes and then, using the removeAttr() snippet, removes the style attributes:

$(document).ready(function(){
   $("* [style]").removeAttr("style");
})
  1. Load CSS file dynamically

Sometimes due to requirements, you will need to load CSS files on demand or dynamically. The following code will load the Demo.css file and add it to the HEAD element:

$(document).ready(function(){
   $("head").append("<link>");
   var css = $("head").children(":last");
   css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "CSS/Demo.css"
   });
});
  1. Apply multiple inline styles together

If you need to apply a couple of styles to your elements, one way is to use multiple statements for each style:

$(document).ready(function(){
  $("div").css('background-color','red');
  $("div").css('color','yellow');
  $("div").css('font-family','Arial');
});

This approach works, but it is not the best practice as it makes code slower. For the same element, jQuery needs to traverse the DOM three times. The better approach would be to do the following:

$(document).ready(function(){
  $("div").css({
  'background-color':'red',
  'color':'yellow',
  'font-family':'Arial'})
});

jQuery allows you to set multiple styles together using object literal. Object literal provides groupings of key/value pair. So all inline styles can become part of object literal inside curly braces as key/value pair.

That’s it.

To sum it up, these jQuery code snippets are pretty useful when handling several different kinds of CSS related functionalities with jQuery. They can make your life simpler, and allow you to bypass all of those regular CSS hacks that need to be implemented on the client side.

Recently Published

article image
»

How to Dynamically Trim Text Using jQuery

This easy beginners jQuery tutorial demonstrates how you can use ...

article image
»

jQuery Snippets: Getting the Current Year

Here’s a fun, simple, and incredibly useful jQuery that you can ...

article image
»

jQuery Snippets: How to Conditionally Enable Submit

One easy way to prevent users from submitting an empty form in a ...

article image
»

How to Use Google Analytics with jQuery Mobile

jQuery Mobile is an HTML5 based web-page framework that’s ...

article image
»

jQuery Snippets: Using jQuery to Check All Boxes

When you’ve given your users a ton of checkbox input fields ...

article image
»

Useful jQuery Code Snippets for Working with Images

Images are an essential part of any website and sometimes working ...

article image
»

How to Use jQuery to Check if Cookies are Enabled

A cookie (not the kind with chocolate chips) is a small piece of data ...

article image
»

A Beginner’s Guide to jQuery’s Selectors

We talk a lot about event methods on this site, but not so much about ...

article image
»

Add Keyboard Shortcut to Anchor Tag Using jQuery

Making a user friendly website can be quite a challenging task. There ...