<div id="teste">teste</div>
var teste_n = '123px';
var _style = window.getComputedStyle(document.getElementById('teste'));
var el = document.getElementById('teste');
document.getElementById('teste').clientWidth;
document.getElementById('teste').offsetwidth;
parseFloat(_style['width'])
el.getBoundingClientRect()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
clientWidth | |
offsetwidth | |
window.getComputedStyle | |
BoundingClientRect |
Test name | Executions per second |
---|---|
clientWidth | 1829593.9 Ops/sec |
offsetwidth | 9064632.0 Ops/sec |
window.getComputedStyle | 1170574.9 Ops/sec |
BoundingClientRect | 1549144.4 Ops/sec |
This benchmark tests different ways to get the width of an HTML element:
Options Compared:
clientWidth
: Returns the visible width of an element, including padding but excluding borders.
offsetWidth
: Returns the total width of an element, including padding and borders. This is often used when you need the absolute width of an element on the page.
window.getComputedStyle(...)['width']
: Uses CSS computed styles to retrieve the width. This value reflects any styling applied through CSS, potentially including inherited properties.
getBoundingClientRect()
: Returns a rectangle object containing information about the position and dimensions of an element relative to the viewport (the browser window). You can access the width
property of this object.
Pros & Cons:
clientWidth
:
offsetWidth
:
window.getComputedStyle(...)['width']
:
getBoundingClientRect()
:
Other Considerations:
getBoundingClientRect()
method gives you information relative to the viewport (the browser window). If your element's position is affected by scrolling, this method will reflect those changes accurately. clientWidth
might be the most straightforward choice.Alternatives:
If performance is a major concern, you could explore using a low-level DOM manipulation library (like Zepto.js) that optimizes these operations.