I am dynamically grabbing a selected drop down option’s text from an array of divs. When I do this:
$("#divID").children("select").eq(0).find('option:selected').text();
Everything works fine. However, when I do this:
$("#divID").children("select option:selected").eq(0).text();
It does not grab the text as expected. I was wondering what I am doing wrong with the latter approach to getting the text. Thanks.
The problem with what you are doing is your use of
children.If you were to change
childrentofindthen it works perfectly. The reason is thatchildrenonly finds elements that are direct children of the set being acted on. So it will only return things that are direct children of#divID. As you can see theoptionelements are not direct children so they can’t be returned.See http://jsfiddle.net/nzhaD/5/
Of course there are some subtle differences between the two of these. Cosnider this HTML:
I’ve cut the options out but your original selector will get id #2 (since it is the only select that is a child of
#divLocationwhereas mine would get the first selected option which will be presumably in id #1.So the moral of the story is do whichever selector does what you actually want it to. 🙂