Search code examples
javascriptjqueryjquery-select2

Select2 - add class to a specific option


I have a select like this:

<select id="mySelect">
    <option>Volvo</option>
    <option value="Cat" class="red">Cat</option>
    <option value="Dog" class="red">Dog</option>
    <option value="Mark" class="green">Mark</option>
    <option value="BMW" class="blue">BMW</option>
    <option value="Snake" class="red">Snake</option>
    <option value="Ferrari" class="blue">Ferrari</option>
</select>

I would like to mantain the same class on select2... looking the code I have seen tha there is no reference between the original select and select2 in the Dom so I can't find search and set...

<ul class="select2-results__options" role="tree" id="select2-mySelect-results" aria-expanded="true" aria-hidden="false">
    <li class="select2-results__option" id="select2-mySelect-result-gagv-Cat" role="treeitem" aria-selected="false"> 
        Cat 
    </li>
    <li class="select2-results__option" id="select2-mySelect-result-0987-Dog" role="treeitem" aria-selected="false"> 
        Dog
    </li>
    <li class="select2-results__option" id="select2-mySelect-result-Fax9-Mark" role="treeitem" aria-selected="false"> 
        Mark
    </li>
    ...
</ul>

I tried to use the "id" of "li", but there is a parameter created by select2 and changes everytime.

I would like to mantain the same classes from standard select... any suggestion?


Solution

  • You can do this by targeting a substring of the id

    var list = document.querySelector("ul[id*='select2']").children;
    var numItems = list.length;
    for (var i = 0; i < numItems; i++) {
        var item = list[i];
        var className = item.id.split("-").pop();
        item.classList.add(className);
    }