I want to create multilevel select2 options with indentation but I don\'t want to use optgroup elements for this because I want to allow select also main catego
You're correct in recognizing that Select2 does not carry the CSS classes from the tags to the results list. This mostly has to do with not explicitly tying the results list to existing tags, and also having a set of sensible defaults. It's easier to add the ability to transfer classes afterwards than it is to remove them.
You can do this by overriding templateResult and getting the original option from data.element (where data is the first parameter).
$('.select2').select2({
templateResult: function (data) {
// We only really care if there is an element to pull classes from
if (!data.element) {
return data.text;
}
var $element = $(data.element);
var $wrapper = $('');
$wrapper.addClass($element[0].className);
$wrapper.text(data.text);
return $wrapper;
}
});
.l2 {
padding-left: 1em;
}
Note that I am also using padding-left instead of text-indent, which is what Select2 usually uses for nested options.