Saturday, 27 February 2021

Determine maximum width a DOM element might grow to be?

I'm interested in querying the maximum size that a DOM element in a browser might grow to be. It is well known that an empty DOM element (without styling) has .clientWidth of 0, but adding text/images/etc. to the element might cause its width to grow. Take for instance the DOM element thisOne in the structure below:

<table style="padding: 20px; border-spacing: 100px">
   <tr>
       <td></td>
       <td>
            <div id="thisOne"></div>
       </td>
   </tr>
</table>

Currently #thisOne.clientWidth === 0 but if I append a large amount of text to it, its width will grow and grow, but not until it reaches document.body.clientWidth because of the columns, padding classes, etc. I am wondering how I can figure out the current maximum width of the object without doing something like:

const thisOne = document.getElementById('thisOne');
thisOne.style.visibility = 'hidden';  // do not display to user.
thisOne.innerHTML = 'blah '.repeat(2000);
const maxWidth = thisOne.clientWidth;
thisOne.innerHTML = '';
thisOne.style.visibility = 'visible';

JQuery based answers are fine, though knowing a pure HTML/JS version would be better.

(In case anyone's wondering, I'm planning on placing an SVG of music notation into the div, but I want it to have nice wrapping onto additional lines by giving the renderer a width to fit before adding it)



from Determine maximum width a DOM element might grow to be?

No comments:

Post a Comment