Tutorial :What's the best way to get the underlying DOM element by ID in jQuery?



Question:

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;  


Solution:1

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.


Solution:2

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


Solution:3

$("#mySelect option:selected").val()  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »