How to add class to select2 element in v4.0

KyleMit picture KyleMit · Jun 11, 2015 · Viewed 33.8k times · Source

This is very similar to this question on how to add class to select2 element, however the answers there appear to target earlier versions of the framework which has undergone some breaking changes in v4.0

According to this issue to add an additional custom class to select2-container, there were several undocumented properties you could pass to the select2 constructor, including: containerCss, containerCssClass, dropdownCss, and dropdownCssClass.

However in version 4 when I run the following code:

$('.select2').select2({
    containerCss: "wrap"
});

I get the following error:

Uncaught Error: No select2/compat/containerCss

How can I pass a class to Select2 in v4.0?

Here's an example in StackSnippets:

Answer

Nulle picture Nulle · Sep 21, 2015

Select2 will store all the information it uses on the original select element. You can access the following information by calling .data('select2') on the original element:

Select2 Data

From there, you can access the $container property to identify the container in the DOM and add the class to that like this:

var $select2 = $('select.select2').select2()

$select2.data('select2').$container.addClass("wrap")

Here's a demo in Stack Snippets

var $select2 = $('select.select2').select2()
$select2.data('select2').$container.addClass("wrap")
body .select2.narrow {
    width: 200px;
}
body .wrap .select2-selection--single {
    height: 100%;
}
body .select2-container.wrap .select2-selection--single .select2-selection__rendered {
    word-wrap: break-word;
    text-overflow: inherit;
    white-space: normal;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script>

<select class="select2 narrow wrap">
  <option value="AL">Really long name that normally</option>
  <option value="AK">Alaska</option>
  <option value="AZ">Arizona</option>
</select>