Silver
Silver

Reputation: 67

Adding a class to a ListItem of an asp:DropDownList from jQuery

I'm trying to add a class from jQuery to the first item of an asp ddl (in case the user didn't select another item before submitting).

i have tried:

$("#my_ddl").options[0].addClass("myErrorClass");

didn't work, any suggestions please? thx in advance.

Upvotes: 2

Views: 160

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You've got a couple of issues here. Firstly jQuery objects don't have an options collection. Secondly, if they did, accessing it by index (ie. using [0]) would return an Element object not a jQuery object, and the former does not have an addClass() method.

To fix this you can use various jQuery methods entirely to add the class, any of these will work:

$('#my_ddl option:first').addClass('myErrorClass');
$('#my_ddl option').first().addClass('myErrorClass');
$('#my_ddl').find('option').first().addClass('myErrorClass');
$('#my_ddl').children('option:first').addClass('myErrorClass');
$('#my_ddl').children('option').first().addClass('myErrorClass');

Alternatively you can use native JS methods:

document.querySelector('#my_ddl option')[0].classList.addClass('myErrorClass');

However, the major caveat to all this that adding classes to option elements for the purposes of styling is not reliable in all browsers. Make sure you test the output is what you expect it to be in all cases.

Upvotes: 1

Related Questions