jQuery(#id).val() vs. getElementById(#id).value
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.
jQuery
does so many nice little error handling things (look below) that I would never write a line of javascript
without jquery
in a browser again.
- First,
val
works on checkbox groups, selects, gets html, and the like. - Second,
$
lets you use sizzle selectors, so in the future, you can easily switch between anID
and aCSS
path. - Third, your code will be so much easier to read and maintain if you
just use
jQuery
, that the time you save maintaining your code outweighs any speedup that you admit your users won't see. Finally,jQuery
is a very popular, very widely used library. They will make$
andval
as fast as they can.