Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  100] [ 5]  / answers: 1 / hits: 20305  / 13 Years ago, mon, may 23, 2011, 12:00:00

What's the difference between classic Javascript code:



document.getElementById('theID')


and the jQuery version:



$('#theID')

More From » jquery

 Answers
16

document.getElementById returns a DOM object. This is the browser's native way of thinking about an element in the page. It has various methods and properties. These can be a little clunky to use.



The jQuery object (created by the $ method) is a wrapper around a DOM element or a set of DOM elements. The normal properties and methods are not available; you get a selection of different methods that make the process of DOM manipulation more intuitive.



The difference is more clear to see with multiple elements in the selection (as you would get with a class selector $('.someClass') for instance, but the methods on a jQuery selection are different to the ones on a native DOM element. They point to the same thing, but they are different ways of thinking about it and dealing with it.






As a final note, you can convert a jQuery selection into its native DOM element(s) with the get method (edit: or the alternative array-like syntax). So



document.getElementById('theID')


is exactly the same as



$('#theID').get(0) // or $('#theId')[0]


Note, however, that you should use the first, as it has much better performance. Only use jQuery if you need the extra functionality it provides.


[#92096] Sunday, May 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;