Ifan Iqbal
Ifan Iqbal

Reputation: 3093

Can we add class attribute in option element?

I want to add class for my option element. Is that valid to add class attribute in HTML option element?

Upvotes: 8

Views: 34542

Answers (4)

Joum
Joum

Reputation: 3245

Yes it is valid.

From the W3Schools website:

The tag also supports the Global Attributes in HTML.

From which the class attribute is a part of. Please note that often, the option tag has formatting issues regarding the browser you are using, so styling it can be a little tricky.

If you're concerned that W3Schools probably isn't the most reliable source of good information, here is a more official link to this subject at W3.org.

Upvotes: 17

Abel Callejo
Abel Callejo

Reputation: 14969

Yes!

In HTML it is valid to add a class attribute to an option element [1].

However...

For CSS implications though, the usability is limited. Especially when it comes to the option tag because it is subject to the operating system's form control handlers [2]. This is the reason why code sample below will not actually work across all browsers.

HTML
<select>
    <option>Centaur</option>
    <option class="colored">Unicorn</option>
</select>
CSS
.colored {
    background-image: url('my-colorful-background.png'); // e.g.: Apple doesn't recognize this rule
}

For JavaScript implications (w/jQuery), the usability is fully supported when it comes to the DOM objects but still bounded with the CSS implications as stated above. Thus, DOM-manipulation code like so... will work.

HTML
<select>
    <option>Centaur</option>
    <option class="colored">Unicorn</option>
</select>
JavaScript with jQuery
var label = jQuery('.colored').html();
console.log( label ); // outputs Unicorn

References

  1. W3C - HTML 4.01 Specification, Forms, The SELECT, OPTGROUP, and OPTION elements
  2. MDN - Styling HTML forms, Why is it so hard to style form widgets with CSS?

Upvotes: 3

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201896

The class attribute is valid for option according to the relevant part of the HTML 4.01 Recommendation. The HTML5 drafts, including HTML5 CR, are even more permissive: they allow class literally on any element.

My guess is that what you really wanted to ask was whether you can style some option elements differently from others, using class attributes and CSS. Then the answer is that this depends on browser – not due to problems with recognizing class attributes but due to implementations of that are partly immune to CSS as regards to styling items in a dropdown list.

Upvotes: 4

Starx
Starx

Reputation: 79069

Yes class belongs to global attributes. Any element can have it.

Source: http://www.w3.org/wiki/HTML/Attributes/_Global

Upvotes: 1

Related Questions