<div id="teste" style="width:100px;">teste</div>
document.getElementById('teste').clientWidth;
document.getElementById('teste').offsetwidth;
document.getElementById('teste').style.width;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
clientWidth | |
offsetwidth | |
style.width |
Test name | Executions per second |
---|---|
clientWidth | 1053460.8 Ops/sec |
offsetwidth | 22319760.0 Ops/sec |
style.width | 3441898.8 Ops/sec |
This benchmark focuses on comparing three different methods of obtaining the width of a DOM element in JavaScript. Specifically, it evaluates:
clientWidth:
document.getElementById('teste').clientWidth;
offsetWidth:
document.getElementById('teste').offsetwidth;
offsetWidth
property provides the layout width of an element, including padding, borders, and scrollbars, but not margins. It represents the total visual size of the element as rendered on the screen.style.width:
document.getElementById('teste').style.width;
From the benchmark results, we can observe the following execution rates for each method:
clientWidth:
offsetWidth:
style.width:
offsetWidth
may be best. For responsive designs focusing merely on content space, clientWidth
can be more appropriate.In summary, the benchmark clearly illustrates that offsetWidth
is the most performant choice for obtaining the width of an element in this context, with clientWidth
and style.width
serving specific needs that may be more relevant depending on the scenario. Choosing the right approach among them depends on the specific requirements of the application in question, including considerations for layout dynamics and performance needs.