To find the first scrollable parent element with JavaScript, we can recursively search for the parent that has scrollHeight
bigger than clientHeight
.
For instance, we can write the following HTML:
<div class="outer">
<div class="inner">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus aliquam iaculis. Pellentesque interdum elit sapien, quis interdum enim laoreet sed. Mauris varius magna ac dapibus molestie. Sed porttitor sapien eget ipsum aliquet, lacinia venenatis lacus finibus. Phasellus in nibh mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed placerat tristique augue, id lacinia massa iaculis eu. Donec sed vestibulum odio. Fusce sit amet congue odio, eu consequat neque. Sed sed mauris id sem malesuada blandit eu at quam.
<div class="content">
<span id='start'>Scroll me into view</span>
</div>
</div>
</div>
Then we write:
const getScrollParent = (node) => {
if (node === null) {
return null;
}
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode);
}
}
const span = document.querySelector('span')
const scrollable = getScrollParent(span)
console.log(scrollable)
to add the getScrollParent
function that takes the HTML DOM node
.
Then it checks if node.scrollHeight
is bigger than node.clientHeight
if the node
isn’t null
.
If it is, then it’s returned.
Otherwise, it calls getScrollParent
with the node.parentNode
to check the node up the DOM tree.
Then we call the function by getting the span with document.querySelector
.
And then we call getScrollParent
with it.
Therefore, we see that scrollable
is the html
element.
One reply on “How to Find the First Scrollable Parent Element with JavaScript?”
The first ‘scrollable’ parent is not necessarily the parent that does the scrolling. If that is the case the values of scrollLeft and scrollTop (jQuery) will be 0. I don’t want to find out the first ‘scrollable’, but the ‘scrolling’ parent. I have to search further.