Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to get a list of classes

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?

like image 498
John Avatar asked May 07 '10 08:05

John


1 Answers

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!
like image 146
MDCore Avatar answered Nov 15 '22 20:11

MDCore