Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between getElementById and jquery $('#smth')

What's the difference between classic Javascript code:

document.getElementById('theID') 

and the jQuery version:

$('#theID') 
like image 352
Andrew Kordampalos Avatar asked May 23 '11 22:05

Andrew Kordampalos


People also ask

What is getElementById in jQuery?

getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page. Jquery $()

What can be used instead of document getElementById?

A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.

What is the difference between $document and get element by ID?

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.

Which is fast document getElementById (' txtName ') or #txtName ')?

The simple answer is document. getElementByID('txtName') is faster than $('#txtName') because jQuery is written on top of javascript. It means internally jQuery is using only native javascript codes.


1 Answers

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.

like image 119
lonesomeday Avatar answered Oct 02 '22 01:10

lonesomeday