Pergunta

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.

Foi útil?

Solução

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'));

Outras dicas

$('#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.

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

$scrollHolder.scrollTop($scrollHolder.scrollHeight);

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top