jQuery(#id).val() vs. getElementById(#id).value
I been searching but I can only find articles talking about one or the other. Which one is better?
I'm making a small web app where performance is not a big concern since there's nothing complex going on.
I considered using jQuery's val()
function since maybe it solves some inconsistency I'm not aware of, but getElementById.value
IS faster (although the end user won't notice.)
So which one should I use? Is jQuery's non-native method worth the lower performance to gain more compatibility?
The biggest advantage of using jQuery().val()
over document.getElementById().value
is that the former will not throw an error if no elements are matched, where-as the latter will. document.getElementById()
returns null
if no elements are matched, where-as jQuery()
returns an empty jQuery object, which still supports all methods (but val()
will return undefined).
There is no inconsistency when using .value
for form elements. However, jQuery.val() standardises the interface for collecting the selected value in select boxes; where as in standard HTML you have to resort to using .options[this.selectedIndex].value
.
If you're using <select>
elements as well, .value
won't work whereas .val()
will.
I would not mind about performance of just getting a value. If you want the best performance, perhaps you shouldn't use a library at all.