How to scroll to an element inside a div with JavaScript?

Spread the love

Sometimes, we want to scroll to an element inside a div with JavaScript.

In this article, we’ll look at how to scroll to an element inside a div with JavaScript.

How to scroll to an element inside a div with JavaScript?

To scroll to an element inside a div with JavaScript, we set the scrollTop property.

For instance, we write

const myElement = document.getElementById("element_within_div");
const topPos = myElement.offsetTop;
document.getElementById("scrolling_div").scrollTop = topPos;

to select the element to scroll to with getElementById.

Then we get the top position of it with offsetTop.

Next we select the scroll container with document.getElementById("scrolling_div").

And set its scrollTop value to do the scrolling.

Conclusion

To scroll to an element inside a div with JavaScript, we set the scrollTop property.

Leave a Reply

Your email address will not be published. Required fields are marked *