Reputation: 5089
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
Reputation: 57105
you have to get the DOM element from jQuery Object
$scrollHolder[0].scrollTop = $scrollHolder[0].scrollHeight;
or
$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.
$scrollHolder.scrollTop($scrollHolder.prop('scrollHeight'));
Upvotes: 5
Reputation: 3125
JQuery selector method always returns an Array of elements. So commented line will not return what you expect.
Upvotes: 0
Reputation: 2972
An other solution is using the correct jQuery-Wrapper for that:
$scrollHolder.scrollTop($scrollHolder.scrollHeight);
Upvotes: 0
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