Given the HTML structure which you state that Select2 is generating, your selector is incorrect. The select2-selection
and select2-selection--single
are both applied to the same element, so the space between them needs to be replaced with a class selector; .
.
Also note that you don't need the if
statement as the title
matches the colour you're setting with .css()
. Try this:
$('.select2-selection.select2-selection--single span.select2-selection__rendered').each(function () {
var title = $(this).attr('title');
$(this).parent().css('background-color', title);
});
Working example