Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 358
Juan Ignacio Avatar asked Sep 06 '11 15:09

Juan Ignacio


People also ask

What is jQuery used for?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

Is jQuery better than JavaScript?

Though JavaScript is the basic language from which jQuery has evolved, jQuery makes event handling, DOM manipulation, Ajax calls much easier than JavaScript. jQuery also allows us to add animated effects on our web page which takes a lot of pain and lines of code with JavaScript.

Is jQuery a JavaScript?

jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming.

Is jQuery used anymore?

“According to Builtwith, of the top 10,000 websites about 88% (or close to 9,000) of them are currently using jQuery as of the beginning of 2019.” jQuery is a well-tested library with a large community of developers who continue to contribute time and effort to modernize and improve the library.


1 Answers

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.

like image 148
Matt Avatar answered Sep 19 '22 06:09

Matt