Josue Espinosa
Josue Espinosa

Reputation: 5089

getElementById vs $('#element')

Before today, I thought that getElementById and $('#element') accomplished the same thing. However, when I tried the following:

// Assuming I have jQuery imported already

var $scrollHolder = $('#element');
var scrollDiv = document.getElementById("element");

scrollDiv.scrollTop = scrollDiv.scrollHeight;
//$scrollHolder.scrollTop = $scrollHolder.scrollHeight;

The commented line didn't work, and the uncommented line did. Do the two methods listed above return different things, or is there an error in my code? Should the commented line be working? I'm very confused and would appreciate insight. Thank you.

Upvotes: 1

Views: 206

Answers (4)

you have to get the DOM element from jQuery Object

$scrollHolder[0].scrollTop = $scrollHolder[0].scrollHeight;

or

.get( index )

$scrollHolder.get(0).scrollTop = $scrollHolder.get(0).scrollHeight;

$('#element'); is jQuery Object. It creates an array of matched Objects . But here you have id-selector so you only get one Object you can refer to the Native DOM object by using array index [index] or using .get(index).

document.getElementById("element"); is a native DOM Object


FYI

jQuery way of doing it.

.scrollTop()

.prop()

$scrollHolder.scrollTop($scrollHolder.prop('scrollHeight'));

Upvotes: 5

dikesh
dikesh

Reputation: 3125

JQuery selector method always returns an Array of elements. So commented line will not return what you expect.

Upvotes: 0

TheHe
TheHe

Reputation: 2972

An other solution is using the correct jQuery-Wrapper for that:

$scrollHolder.scrollTop($scrollHolder.scrollHeight);

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59292

$('#id) returns jquery objects which doesn't have native DOM properties and document.getElementById('id') returns you a native DOM element which has scrollTop property.

Note that you can make any DOM element act as jquery object by wrapping it with $( ) and you can make jquery object to DOM element by accessing index.

Upvotes: 1

Related Questions