What is the scrollWidth property in DOM?

Overview

scrollWidth in DOM is an HTML property that returns the scroll width of the HTML element.

The scroll width refers to the entire width of that element in the HTML page, even if it is not viewable due to the overflow property.

The element’s scroll width includes the width assigned in CSS property plus the padding, but it does not include the margin, border, or scrollbar.

Example

Let us see an example to find the scroll width of the div element.

Console

Code explanation

  • In lines 5-9: We have CSS properties for id elem, where we define backgroud-color, padding, and width.

  • In line 14: We have a paragraph p tag to display text.

  • In line 16: We have a button tag that has a change() function that is bound with the onclick event.

  • In line 18: We have a div element with an ID elem that we will use to get the element object.

  • In lines 23-27: We define a change() function that will be called with the click of the button from the HTML page. We use document.getElementById() to get the desired element of DOM, and then we apply scrollWidth, which will return the scroll width of the element. We print the value returned by scrollWidth on the console.

Output

We have successfully retrieved the scroll width of a div element. The console prints the total width, which is 5020px. The width also includes the padding, therefore the width of div(5000px) + top and bottom padding(10px + 10px = 20px) is 5020px. Remember that scroll width does not include the border, scrollbar, or margin.