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

心已入冬 提交于 2019-12-01 12:34:45

问题


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:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/989865/whats-the-best-way-to-get-the-underlying-dom-element-by-id-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!