Categories
JavaScript Answers

How to Find the First Scrollable Parent Element with JavaScript?

Spread the love

Sometimes, we want to find the first scrollable parent element with JavaScript.

In this article, we’ll look at how to find the first scrollable parent element with JavaScript.

Find the First Scrollable Parent Element with JavaScript

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.

Conclusion

To find the first scrollable parent element with JavaScript, we can recursively search for the parent that has scrollHeight bigger than clientHeight .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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