Choosing2 - incorporate a style to a distinct choice

Let's talk about a select element I have:

<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>

My question is, how can I maintain the same classes on select2 as well? While looking at the code, I noticed that there isn't a clear link between the original select and select2 in the DOM.

<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 attempted to use the "id" of the li elements, but was faced with a challenge - select2 creates a parameter that changes each time.

If you have any suggestions on how I can keep the same classes from the standard select into select2, please let me know! Thank you!

Answer №1

To achieve this, one method is to specifically target a portion of the id

const items = document.querySelector("ul[id*='select2']").children;
const totalItems = items.length;
for (let index = 0; index < totalItems; index++) {
    const currentItem = items[index];
    const targetClass = currentItem.id.split("-").pop();
    currentItem.classList.add(targetClass);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Applying hover effect to material-ui IconButton component

As stated in the React Material-UI documentation, I have access to a prop called hoveredStyle: http://www.material-ui.com/#/components/icon-button I intend to utilize the IconButton for two specific purposes: Make use of its tooltip prop for improved ac ...

Modifying several items with Ramda's lens

I am currently working with a data structure that is structured similarly to the following: var data = { "id": 123, "modules": [{ "id": 1, "results": [{ "status": "fail", "issues": [ {"type": "ch ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...

What is the best way to send multiple parameter values from jQuery to a Laravel controller?

I am facing an issue with my code where I don't understand how to send multiple parameters from jQuery to the controller. Below is the route: Route::get('/listcdix/{id}/detail/{asnumber}', ['as' => 'remindHelper', & ...

Exploring the HTMLUnknownElement using jQuery.find() and an XML file

Trying to load an XML document (specifically, an RSS feed) through an Ajax request to parse and incorporate information into my webpage. Surprisingly, the code functions properly in Firefox, Opera, Chrome, and Safari but encounters issues with IE7. Upon i ...

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

Use Javascript or Jquery to dynamically change the background color of cells in HTML tables based on their numerical

I am working with a collection of HTML tables that contain numbers presented in a specific style: <table border="1"> <tr> <th>Day</th> <th>Time</th> <th>A</th> <th>B</th> &l ...

Error: Running the command 'yarn eg:'live-server'' is not a valid internal or external command

Currently, I am utilizing yarn v1.6.0 to manage dependencies. I have globally installed live-server by running the following command: yarn global-add live-server However, upon executing it as live server, I encounter the following error: 'live-ser ...

Endless rotation with stunning magnification feature

My goal is to create a responsive carousel with auto-play infinite loop functionality, where the center item always occupies 70% of the viewport width. Currently, I have achieved a similar result using the Slick library: https://codepen.io/anon/pen/pBvQB ...

Tips on getting Qtip2 Growl to start at the bottom position

After utilizing Qtip2 in two of my previous projects, I am eager to try out a new feature called Growl. You can find more information about Growl here. My goal is to have the growl start from the bottom instead of above. I have attempted to reverse the c ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Methods to Maintain Consistent HTML Table Dimensions utilizing DOM

I am facing an issue with shuffling a table that contains images. The table has 4 columns and 2 rows. To shuffle the table, I use the following code: function sortTable() { // Conveniently getting the parent table let table = document.getElementById("i ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

Retrieve live data from a Python script using jQuery and PHP for immediate usage

How can I show the current temperature on a webpage? My setup involves using a Raspberry Pi 3 with the Jessie OS and Chromium as the browser. To achieve this, I have placed a Python script inside a loop for a countdown timer. The script is triggered ever ...

Is it possible for Javascript to handle a string of 27601 characters in length?

I have created a webmethod that returns an object containing strings. Each string in the object is of length 27601. This pattern continues for all array members - str(0) to str(n). When my webmethod returns this exact object, I encounter an issue on the c ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

Error 404 in Angular HTTP Request

I'm encountering a 404 error while attempting to send a post request, along with a 'possibly unhandled rejection' error. Given my limited experience with Angular, any advice would be greatly appreciated. I've gone through the documentat ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...