How to Set Width of a New Container Element to Match an Existing Element's Width in JavaScript?

I’m working on a project where I need to dynamically create a new container element and append an existing element into it. My goal is to ensure that the new container element has the same width as the existing element, regardless of how that width is defined (e.g., auto, max-content, inline styles, or specific pixel values).

here's what I have done done so far

    <div class="container" id="container-element">
      <h1>hello!</h1>
    </div>

    <script>
      const containerElement = document.getElementById('container-element');

      // Get the computed width of the container element. 
      // Even if no explicit width is set (e.g., using `auto`), 
      // this will return a pixel value (like `256px`), 
      // which may not reflect the original width setting (e.g., `auto`, `max-content`, etc.).
      const containerElementWidth = window
        .getComputedStyle(containerElement)
        .getPropertyValue('width'); // not working, it's giving me a pixel value like `256px`, expected value to be `auto`

      const newContainerElement = document.createElement('div');
      const newContainerElementStyle = {
        width: containerElementWidth,
        /*
          other code here
        */
      };
      Object.assign(newContainerElement.style, newContainerElementStyle);
      newContainerElement.append(containerElement);

      // this function is just going to append the new container element directly to the position of the previous container element
      appendNewContainer(newContainerElement);
    </script>


How can I obtain the width of containerElement regardless of how it’s styled (e.g., using max-content, auto, or explicit pixel values)?
Was this page helpful?