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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With