I have a select like this:
<select id="mySelect">
<option>Volvo</option>
<option value="Cat" >Cat</option>
<option value="Dog" >Dog</option>
<option value="Mark" >Mark</option>
<option value="BMW" >BMW</option>
<option value="Snake" >Snake</option>
<option value="Ferrari" >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 role="tree" id="select2-mySelect-results" aria-expanded="true" aria-hidden="false">
<li id="select2-mySelect-result-gagv-Cat" role="treeitem" aria-selected="false">
Cat
</li>
<li id="select2-mySelect-result-0987-Dog" role="treeitem" aria-selected="false">
Dog
</li>
<li 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?
CodePudding user response:
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);
}