Search code examples
javascripthtmlcssfieldset

How to get display width of inline-block fieldset from javascript


If you have a fieldset with display: inline-block, it has a width dependent on its contained element. You can see it, but assuming:

<fieldset id='fs' style='display: inline-block'>
  <input type=number>
</fieldset>

<script>
  var fs=document.getElementById("fs");
  console.log("fs.width:",fs.width);
</script>

The only output will be:

fs.width: undefined

After trying a lot of things I finally was able to get it like this:

<script>
  var fs=document.getElementById("fs");
  var fsrects=fs.getClientRects();
  var fswidth=fsrects[0].right-fsrects[0].left;
  console.log("fswidth:",fswidth);
</script>

and then the output is

fswidth: 98.6640625

There must be an easier way! Help!!!


Solution

  • You are probably looking for offsetWidth.

    The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width.

      var fs=document.getElementById("fs");
      console.log("fs.width:",fs.offsetWidth);
    <fieldset id='fs' style='display: inline-block'>
      <input type=number>
    </fieldset>