Add class to select2 element

jQuery uses JSON objects to initialize, so I guess this one will as well:\

$("#myBox").select2({ containerCssClass : "error" });

If you want to add/remove a class you can do this after you initialized it

$($("#myBox").select2("container")).addClass("error");
$($("#myBox").select2("container")).removeClass("error");

The above function gets the DOM node of the main container of select2 e.g.: $("#myBox").select2("container")

Important
You will need to use the container method to get the container since you won't edit the SELECT directly but select2 will generate other HTML to simulate a SELECT which is stylable.


For those wandering here from google, the property containerCssClass has a misleading name since it doesn't actually add any classes to the container element, but rather to the selection element. You can see this when you inspect the generated html.

I came across a nice little hack here that allows you to apply your css class to the container by adding it to the theme property, like so:

$('#my-select').select2({
    theme: "bootstrap myCssClass",
});

For already initialized select2 element I have tried @Niels solution but it resulted in an error: Uncaught TypeError: Cannot read property 'apply' of undefined

Went into the source and this has been working instead:

$('#myBox').data('select2').$container.addClass('error')
$('#myBox').data('select2').$container.removeClass('error')

Using select2 v4.0.3 full


According to the documentation, containerCssClass is only a constructor property. The best you're probably going to be able to do is reinitialize it when you get an error via:

$("#myBox").select2({
    containerCssClass: "error" 
});

Note from comments: If you get Uncaught Error: No select2/compat/containerCss(…), you need to include the select2.full.js version instead of the basic one