Initially, the code consisted of a plain table with a select tag:
<table class="table">
<tr>
<td>
<select id="e2">
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="red">Red</option>
</select>
</td>
</tr>
</table>
Using jQuery functions, the selection is transformed into a list of nested spans:
<table class="table">
<tr>
<td>
<b class="tablesaw-cell-label">Status</b>
<span class="tablesaw-cell-content">
<select tabindex="-1" class="select2-hidden-accessible" id="e2" aria-hidden="true">
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="red">Red</option>
</select>
<span class="select2 select2-container select2-container--default select2-container--below" style="width: 64px;" dir="ltr">
<span class="selection">
<span tabindex="0" class="select2-selection select2-selection--single" role="combobox" aria-expanded="false" aria-haspopup="true" aria-labelledby="select2-e2-container">
<span title="Green" class="select2-selection__rendered" id="select2-e2-container">Green</span>
<span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
</span>
</td>
</tr>
</table>
I want to dynamically change the background color of each element based on its title after the page loads. Below is the current function for changing colors. It executes once the dropdown list is created and formatted by the select2
functionality.
$(document).ready(function () {
$('#e1').select2();
$('#e2').select2();
$('.select2-selection.select2-selection--single span.select2-selection__rendered').each(function () {
var title = $(this).attr('title');
console.log(title);
if (title === 'Green') {
$(this).parent().css('background-color', 'green');
}
if (title === 'Yellow') {
$(this).parent().css('background-color', 'yellow');
}
if (title === 'Red') {
$(this).parent().css('background-color', 'red');
}
});
});
While I've managed to simplify the code and apply a uniform color to all elements, my goal is to individually style each selection element based on its title without affecting others. This remains a challenge.