简体   繁体   中英

Add span inside <option> tag and style it

I would like to add span before text inside <option> tag and style it (it should represent color in select menu). However it does't seem to work...

How to make this piece of code working?

JsFiddle: http://jsfiddle.net/bartuz/08e0L9j2/2/

It seems example above does work in Firefox only... what about other browsers?

This will depend on your web browser. In the latest version of Firefox, it works fine. However, it doesn't work in the latest version of Internet Explorer.

Your question is a bit loaded - and I suspect that's why it got downvoted - you are asking why it's not working, rather than how to get it to work.

It's not working because it's not really a supported feature of selectboxes (yet!)

I'd suggest you look into using JavaScript to achieve the same result (and specifically, the jQuery UI selectmenu ) which should support this type of 'advanced' select box.

You shouldn't rely on the fact that your hack works on Firefox, does not mean it should on Chrome too.

Anyway, styling selects was always frustrating and there's no easy way to customize native select elements.

If you're looking for a way to style the native select elements, maybe this will help:
https://catalin.red/making-html-dropdowns-not-suck/

An option element isn't allowed to have child elements. I've extended your same answer, but instead applied the background color to the option element as demonstrated in this jsfiddle link: https://jsfiddle.net/go4zee/6L0jjjoa/

$('#tag_item_color option').each(function () {
    var color = $(this).text();
    console.log(color);
    $(this).closest("option").css({"background-color":color});

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM