Use jQuery to get a list of classes

2019-02-16 15:43发布

问题:

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?

回答1:

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!


回答2:

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;
}