views:

753

answers:

3

This sounds like a really basic question. Let's say I have the following Form element

<select id="mySelect">

...

Using jQuery, let's say I want to get it by ID so I can directly access one of its attributes like selectedIndex.

I don't think I can use

var selectedIndex = $("#mySelect").selectedIndex;

because the # selector returns an Array of Elements. If I wish to actually access the select DOM element, then I have to call

var selectedIndex = $("#mySelect").get(0).selectedIndex;

Is this correct? Is there a selector that will let me get directly to the DOM element without having to make an "extra call" to get(0)?

I ask because I'm coming from Prototype where I can just say:

var selectedIndex = $('mySelect').selectedIndex;
+1  A: 

$("#mySelect").val() will do the trick.

ScottE
A: 
$("#mySelect option:selected").val()
Marwan Aouida
+2  A: 

There are jQuery ways to get the value of the <select> that don't require you to access the actual DOM element. In particular, you can simply do this to get the value of the currently selected option:

$('#mySelect').val();

Sometimes, however, you do want to access a particular DOM attribute for whatever reason.

While the .get(0) syntax you provided is correct, it is also possible without the function call:

$("#mySelect")[0].selectedIndex;

A jQuery collection behaves as an array-like object and exposes the actual DOM elements through it.

Paolo Bergantino