9

Scenario:

I got 2 jQuery expressions:

/* A */ $('select').find('option[selected]');
/* B */ $('select').find('option').filter('[selected]');

which mean (let's assume there's only one select in the document, for simplicity):

  • A: Get the select, then find all option descendants that has an attribute named selected.
  • B: Get the select, then find all option descendants, then filter by those who has an attribute named selected.

Expected Behaviour:

A and B should give the same result.

Actual Behaviour:

After the user changed the selection in the dropdown,

  • A returns the default selected option.
  • B returns the new selected option.

Question:

So why are they different? Is my understanding about CSS selectors wrong?

Live Demo:

Live demo is here here.

Source Code:

HTML:

<select>
 <option value='p'>p</option> 
 <option value='q' selected>q</option>
 <option value='r'>r</option> 
 <option value='s'>s</option> 
</select>


<input type='button' value='click me!'/> <br/> 
 ResultA : <span id='ResultA'>
    here
</span> <br/> 
 ResultB : <span id='ResultB'>
    here
</span> <br/> 

Javascript:

function SetResult(ResultObj, ElementObj) {
    ResultObj.text("length=" + ElementObj.length + " " + "val()=" + ElementObj.val());
}

$(function() {
    $('input[type=button]').click(function() {
        var SelectObj = $('select');
        SetResult($("#ResultA"), SelectObj.find('option[selected]'));
        SetResult($("#ResultB"), SelectObj.find('option').filter('[selected]'));
    });
});

Test Result:

+---------------------------+--------------+---------------------+---------+-----+
|          Browser          | Environment  |       jQuery        |    A    |  B  |
+---------------------------+--------------+---------------------+---------+-----+
| Chrome 22.0.1229.94m      | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Chrome 23.0.1271.64 m     | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Firefox 15.0.1            | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Firefox 16.0.2            | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| IE 6                      | WinXP        | 1.8.2, 1.7.2, 1.6.4 | *new*   | new |
| IE 9                      | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Opera 12.02               | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Opera 12.10               | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Safari 5.1.7 (7534.57.2)  | Win7         | 1.8.2, 1.7.2, 1.6.4 | default | new |
+---------------------------+--------------+---------------------+---------+-----+
| Chrome 22.0.1229.94       | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Chrome 23.0.1271.64       | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Firefox 13.0              | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Firefox 14.0.1            | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Firefox 16.0.2            | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Opera 12.01               | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Opera 12.10               | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Safari 6.0.1 (7536.26.14) | MacOS 10.7.5 | 1.8.2, 1.7.2, 1.6.4 | default | new |
+---------------------------+--------------+---------------------+---------+-----+
| Chrome 21.0.1180.82       | iOS 4.3.5    | 1.8.2, 1.7.2, 1.6.4 | default | new |
| Opera 7.0.5               | iOS 4.3.5    | 1.8.2               | default | new |
| Safari                    | iOS 4.3.5    | 1.8.2, 1.7.2, 1.6.4 | default | new |
+---------------------------+--------------+---------------------+---------+-----+
  • default means it returns the default selected option.
  • new means it returns the new selected option.

As you can see, all browsers except IE6 give different results.

4
  • 2
    Your understanding of CSS selectors seems sound. However, jQuery does not always base selectors on the source markup. This is especially true, I've found, for attribute selectors with values that can change. No idea why jQuery would treat these inconsistently, though.
    – BoltClock
    Oct 30, 2012 at 11:14
  • 2
    Side note: using option:selected instead of option[selected] for the #ResultA will produce the same output as #ResultB.
    – sp00m
    Oct 30, 2012 at 11:17
  • @sp00m: I'm starting to really really hate Sizzle a lot.
    – BoltClock
    Oct 30, 2012 at 11:25
  • 1
    There was an issue with these selectors not returning the same value in jQuery versions older than 1.7 - see this bug report
    – Mottie
    Oct 30, 2012 at 11:47

5 Answers 5

3

The Sizzle engine checks the selected property of an element (which contains the current value) rather than the attribute which contains the original (default) value.

See https://github.com/jquery/sizzle/blob/master/sizzle.js#L788

What I haven't figured out yet is why your second selector apparently invokes Sizzle, but the first one doesn't seem to.

In any event, the property is what you should be checking rather than the attribute, so you should be using the :selected pseudo-selector, and not [selected]

2
  • 1
    dmethvin explains the difference in this issue: the problem of :selected going through the JavaScript path of Sizzle and looking a properties, whereas [selected] goes through the querySelectorAll path and looks at attributes. (Unless there is some other non-qSA selector in the string, such as [selected]:first.)
    – Mottie
    Oct 30, 2012 at 11:50
  • @Mottie indeed, except that I used the debugger and found that .filter('[selected]') didn't go through the :selected Sizzle code. Odd...
    – Alnitak
    Oct 30, 2012 at 11:55
1

when you write option[selected] it will search for the selected attribute/property instead of that you should use option:selected if you have readonly property and you code option[readonly] it will return s

$('[attribute]') will selects elements that have the specified attribute, with any value.
for more information : Has Attribute Selector [name]

Fiddle

<select>
 <option value='p'>p</option> 
 <option value='q' selected>q</option>
 <option value='r'>r</option> 
 <option value='s' readonly>s</option> 
</select>  
1

What should the expressions return?

[selected] matches all elements that has a selected attribute, with any value (references: W3C, jQuery).


Why are the results inconsistent?

I have submitted a bug report to jQuery here. It is marked as a duplicate of another bug report which is now fixed.


Any solutions?

To get the current selection:

Use the :selected selector (live demo here):

$('select').find('option').filter(':selected'); /* Supposedly faster */
or
$('select').find('option:selected');            /* Supposedly slower */

Note that the 2nd expression is supposedly slower, according to the doc.

Because :selected is a jQuery extension and not part of the CSS specification, queries using :selected cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.

To get the default selection:

For jQuery 1.9+, use any of the expressions as in the question, i.e.

/* A */ $('select').find('option[selected]');
/* B */ $('select').find('option').filter('[selected]');

For jQuery 1.6+, make use of the defaultSelected property (live demo here, references: w3schools, Mozilla, MSDN, MSDN):

$('select').find('option').filter(function() {
    return $(this).prop('defaultSelected');
});
0

This depends on how the DOM is constructed by the browser.. using option[selected] jQuery search for an option element having the selected attribute which in some cases it doesn't applied

You should use

SelectObj.children(':selected')
1
  • .filter('[selected]') filters options having the selected attribute too... The question is why.
    – sp00m
    Oct 30, 2012 at 11:21
0

Your implementation is wrong it's not

find('option[selected]')

It should be,

SelectObj.find('option:selected')

Here's the edited fiddle:

http://jsfiddle.net/ugXtx/6/

and reference:

http://api.jquery.com/selected-selector/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.