简体   繁体   中英

How can I access javascript methods from jQuery selectors

I have this plain js:

var innerText  = document.getElementById("TaskId").options[0].text;

And I was wondering how to convert it to jQuery:

var innerS = $("#TaskId");
var innerText = innerS.options[0].text;

This throws an error:

innerS.options is undefined

EDIT

In accordance with some of the debate I threw a quick speed test together:

js:

var startDat = Date.now();
for (var c = 0; c < 100000; c++) {
    var com = $("#TaskId").get(0);
}
var endDat = Date.now();
alert("jQ.get(0) took " + (endDat - startDat) + "ms");


var startD = Date.now();
for (var co = 0; co < 100000; co++) {
    var com = $("#TaskId")[0];
}
var endD = Date.now();
alert("jQ[0] took " + (endD - startD) + "ms");

var startDa = Date.now();
for (var comp = 0; comp < 100000; comp++) {
    var compa = document.getElementById("TaskId");
}
var endDa = Date.now();
alert("js took " + (endDa - startDa) + "ms");

results:

jQ.get(0) took 1042ms
jQ[0] took 1057ms
js took 136ms

A jQuery object contains an array of DOM elements. If you want direct access to the DOM elements, there are a number of ways to get that direct access. For example, you can directly get the first DOM element with this:

var innerS = $("#TaskId").get(0);

Now innerS is the actual DOM element and not a jQuery object any more.

For fastest execution time, use:

var innerS = document.getElementById("TaskId");

jQuery can be fast to code with, but is not always the fastest for execution time as jQuery objects carry some overhead with them (constructing them, sorting DOM elements, etc...).

You can get the entire DOM array like this:

var optionElements = $("option").get();

Of course, one of the reasons for using jQuery objects is that they have a set of cross-browser methods that make it easy to just use their methods instead of the direct DOM methods in some cases. In your particular case, you could get the innerText like this:

var text = $("#TaskId").text();

A jQuery object is essentially just a wrapper around a DOM element so in order to access the DOM element itself you can use either .get(0) or [0]:

$('#TaskId').get(0).options[0].text;

// OR

$('#TaskId')[0].options[0].text;

Two possible solutions:

var innerText = innerS[0].options[0].text; 
// Are you sure about .text? I never used it.

or

var innerText = $("#TaskId option:first").text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM