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

Screen Shot 2017-04-23 at 10.15.41 AM
»

How to Use jQuery to Create a Sticky Navigation on Scroll

Creating “sticky” elements is something that can often be ...

article image
»

How to Use jQuery’s Keystroke Methods

jQuery has a few built-in keystroke methods that are all triggered by ...

article image
»

How to Change iFrame Styling Using jQuery

If you’ve ever had the displeasure of working with iFrames, ...

article image
»

How to Use jQuery to Create Blinking Text

Blinking text is one of those cool features that you never actively ...

article image
»

Convert Images to Black and White using jQuery

Converting an image to black and white is no longer a manual event. ...

article image
»

How to Disable Right-Click Menu Using jQuery

There can be dozens of reasons why you may want to disable right ...

article image
»

How to Optimize jQuery Code for Better Performance

jQuery is the most popular client side library, in fact almost every ...

article image
»

Using Head.js to Load All Your JavaScript

In the past few years, client side frameworks/libraries have become ...

article image
»

How to Detect Browser Using jQuery

One of the more frustrating parts of creating a new web project is ...