4

Which is faster: $("#element")[0].value or $("#element").val()? If the former is faster, what is the purpose of the latter?

1
  • Implementation hiding and encapsulation, plain and simple. Commented Mar 13, 2011 at 3:45

2 Answers 2

10

$("#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.

Sign up to request clarification or add additional context in comments.

8 Comments

E.g., the value (ahem) of .val() is that it smooths out some differences for you that you'd otherwise have to handle yourself.
@T.J.Crowder - I tried to enumerate all of those above, hopefully it helps a bit.
@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.
@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>.
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?
|
1

the same as $("#element") being slower than document.getElementById('element');

ease of use, consistency in the framework, hiding of cross-browser implementation (inconsistencies, not in the particular example but that is the concept of frameworks)..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.