Reputation: 82297
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
Upvotes: 2
Views: 132
Reputation: 7063
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;
Upvotes: 3
Reputation: 707736
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();
Upvotes: 4
Reputation: 71939
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();
Upvotes: 2