Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!