Can we add class attribute in option element?

Yes it is valid.

From the W3Schools website:

The <option> 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.

EDIT: Since I wrote this answer, it has come to my attention that W3Schools probably isn't the most reliable source of good information. The previous answer isn't at all wrong, but it came from a source that has proven to be somewhat inconsistent/incomplete. As such, I think I should also append a more official link to this subject here.


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.


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?