4

I want to access the select option jQuery objects as such:

var $options = $('select').children(); var $someOption = $('[value="some_value"]', $options); var $anotherOption = $('[value="another_value"]', $options); 

but neither $someOption or $anotherOption look like any of the elements in $('select').

I believe I know how to compose the one line selector but since I'm accessing various options, I wanted to use the $options handle for readability and performance instead.

What is wrong with the code and/or rationale?

3
  • 1
    Did you accidentally exclude the $ from the selectors for $someOption and $anotherOption? Commented Jan 28, 2013 at 23:47
  • 1
    You seem to be missing the $ for the jQuery function on your second and third selectors. Commented Jan 28, 2013 at 23:47
  • @ExplosionPills, jmoerdyk, thank you, I now fixed the OP typos. Commented Jan 29, 2013 at 18:37

2 Answers 2

5

You have to use jQuery's filter method:

var $options = $('select').children(); var $someOption = $options.filter('[value="some_value"]'); var $anotherOption = $options.filter('[value="another_value"]'); 
Sign up to request clarification or add additional context in comments.

2 Comments

Passing in a jQuery object as the second parameter acts as the context to select from, so it does the same thing as your code EDITED (this statment is incorrected)
@JustinBicknell - Nope. Passing in a context searches for descendants, and is equivalent to this: $options.find('[value="some_value"]')
1

In order to use the context parameter, don't call .children().

var $select = $('select'); var $someOption = $('[value="some_value"]', $select); var $anotherOption = $('[value="another_value"]', $select); 

4 Comments

This'll traverse the DOM each time. Filtering only looks at the set being filtered.
@JosephSilber True, although it only has to traverse the subset of the DOM below the select, not the entire DOM, so it's not too bad.
True, but what benefit does it offer over filtering?
@JosephSilber It's less verbose, some may find it more readable, which is one of the criteria the OP is looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.