Which is faster: $("#element")[0].value or $("#element").val()? If the former is faster, what is the purpose of the latter?
-
Implementation hiding and encapsulation, plain and simple.Lightness Races in Orbit– Lightness Races in Orbit2011-03-13 03:45:36 +00:00Commented Mar 13, 2011 at 3:45
Add a comment
|
2 Answers
$("#element")[0].value is faster, native code is always faster.
Even faster would be document.getElementById("element").value.
The .val() function is to work for all input types, including <textarea> and <select> elements. Underneath, for everything that's not an <option> or a <select> or a <input type="radio"> (in some cases) it gets the .value.
8 Comments
T.J. Crowder
E.g., the value (ahem) of
.val() is that it smooths out some differences for you that you'd otherwise have to handle yourself.Nick Craver
@T.J.Crowder - I tried to enumerate all of those above, hopefully it helps a bit.
user113716
@T.J., @Nick - Are you aware of any other
<select> issues besides the IE6 issue where its <option> elements don't have a value attribute? That's the only one I know about.Nick Craver
@patrick - IE has issues where you can't set a
<select> element's .innerHTML to update the <option> list properly, but that's a result of them inheriting from the windows form control....BRILLIANT idea that was (same reason it's on top of everything but an <iframe>.Explosion Pills
I see. In that case would you recommend using the first (or even document.getElementById()) at all times, or is it okay to use the framework functions for consistency and sensibility? That is, will the speed of the code suffer noticeably?
|