MainelyDesign.com Blog

jQuery Object getClasses System

Posted on 08/29/2014 at 11:04 am by Kevin Wentworth
Viewed 6,108 times | 0 comments

After having to create a list of classes on an element, I decided that it was time to have a method to pull all of an objects classes into one returnable array. This is extremely useful for class-based tagging and object finding.

Requires jQuery v1.2+

The getClasses Method

  1. jQuery.fn.getClasses = function() {
  2.     var classes = [];
  3.     var objClass = $(this).attr('class');
  4.     objClass = objClass.split(' ');
  5.    
  6.     $.each(objClass, function(index, value) {
  7.         if(value !== "") {
  8.             classes.push(value);
  9.         }
  10.     });
  11.    
  12.     return classes;
  13. }

Using It

Instead of doing anything fancy, let's just print out the classes that the div has, into its child span

  1. var theClasses = $('#element').getClasses();
  2. $("#element span").append(theClasses.join(', '));

Good Luck, Fellow Programmers.

Bookmark and Share

Tags for jQuery Object getClasses System

Jquery | Javascript | Tutorial

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design