joseph-fugate joseph-fugate - 1 year ago 118
HTML Question

How can I update option class of select dropdown?

I'm trying to update the class of select option. For example, I'd like to update the class of the selected option to add cbp-filter-item-active. I can see that the browser is taking the data-filter change. However, the issue is that in chrome the option class doesn't update to add cbp-filter-item-active to the selected option.

Here's my HTML code:

<select id="js-filters-lightbox-gallery1" class="cbp-l-filters-dropdown cbp-l-filters-dropdown-floated">
<option value="*" data-filter="*" class="cbp-filter-item-active cbp-filter-item">All</option>
<option value=".identity" data-filter=".identity" class="cbp-filter-item">Identity</option>
<option value=".web-design" data-filter=".web-design" class="cbp-filter-item">Web Design</option>
<option value=".print" data-filter=".print" class="cbp-filter-item">Print</option>
</select>


Here's my Script:

function myFunction() {
var e = document.getElementById("js-filters-lightbox-gallery1");
var rc = e.options[e.selectedIndex].dataset.filter;
alert(rc)
}

Answer Source

Remove the class from all items

$("#js-filters-lightbox-gallery1>option.cbp-filter-item-active").removeClass("cbp-filter-item-active");

Add the class to the selected item

$("#js-filters-lightbox-gallery1>option:selected").addClass("cbp-filter-item-active");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download