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.
Code explanation
-
In lines
5-9: We haveCSSproperties for idelem, where we definebackgroud-color,padding, andwidth. -
In line
14: We have a paragraphptag to display text. -
In line
16: We have a button tag that has achange()function that is bound with theonclickevent. -
In line
18: We have adivelement with an IDelemthat we will use to get the element object. -
In lines
23-27: We define achange()function that will be called with the click of the button from the HTML page. We usedocument.getElementById()to get the desired element of DOM, and then we applyscrollWidth, which will return the scroll width of the element. We print the value returned byscrollWidthon 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.