Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

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.

Solution 2:

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.

Solution 3:

Yes!

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

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 . This is the reason why code sample below will not actually work across all browsers.

HTML
<select>
    <option>Centaur</option>
    <optionclass="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>
    <optionclass="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?

Solution 4:

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

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

Post a Comment for "Can We Add Class Attribute In Option Element?"