10

I have a un-ordered (ul) HTML list. Each li item has 1 or more classes attached to it. I want to go through this ul list and get all the (distinct) classes. Then from this list create a list of checkboxes whose value matches that of the class and also whose label matches that of the class. One checkbox for each class.

What is the best way to do this using jQuery?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John
  • 21,047
  • 43
  • 114
  • 155
  • nothing so far. Just got the list set up. I wasn't sure where to even start. – John May 07 '10 at 09:27
  • possible duplicate of [Get Class List for Element with jQuery](http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery) – lebolo Mar 24 '14 at 15:52

2 Answers2

18

Try this:

// get the unique list of classnames
classes = {};
$('#the_ul li').each(function() {
    $($(this).attr('class').split(' ')).each(function() { 
        if (this !== '') {
            classes[this] = this;
        }    
    });
});

//build the classnames
checkboxes = '';
for (class_name in classes) {
    checkboxes += '<label for="'+class_name+'">'+class_name+'</label><input id="'+class_name+'" type="checkbox" value="'+class_name+'" />';
};

//profit!
MDCore
  • 17,583
  • 8
  • 43
  • 48
  • 1
    You should check whether `this` is the empty string before adding it to the list, in case there are extra spaces in the class declaration. – Tgr May 07 '10 at 09:16
  • 1
    You need to check against `''`. If you split by a space, you will never get a space, but `'a..b'.split('.')`will give `['a', '', 'b']` – Tgr May 08 '10 at 20:48
  • 2
    Would this only work for a list or should it work if I want to get all the different classes for tr's in a table? because it doesn't want to work for me, within the each function i get undefined for `$(this).attr('class')` – jonnie Dec 07 '12 at 15:34
  • is there any way to get specific classes only? say the classes that starts with `tag-` with wildcard? thanks – Towfiq Jun 01 '14 at 09:32
3

i also needed this functionality but as a plugin, thought i share it...

jQuery.fn.getClasses = function(){
  var ca = this.attr('class');
  var rval = [];
  if(ca && ca.length && ca.split){
    ca = jQuery.trim(ca); /* strip leading and trailing spaces */
    ca = ca.replace(/\s+/g,' '); /* remove doube spaces */
    rval = ca.split(' ');
  }
  return rval;
}
Florian F
  • 4,044
  • 3
  • 30
  • 31