Garth Marenghi Garth Marenghi - 4 months ago 12
jQuery Question

Selecting every first option of multiple select elements

I have an html file with multiple select elements. What is needed is that the text of every first option of a select element is changed with jQuery. The answer given is

$('select').children().first().html('changed!');
. But this does not change all the first option texts, only the first one.

What is the proper way to go about this?

Answer

Use .each():

$('select').each(function() {
    $(this).children().first().text('changed!');
});

Note that you should use text(), not html() in this case, as the content of <option> elements is supposed to be plain text.

Alternatively, you can select the first option elements directly, avoiding the use of children() and first():

$('select>option:first-child').each(function() {
    $(this).text('changed!');
});