Ensuring H1 is within defined width when content is changed programmatically

There are two headings defined as below:

<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. At risus viverra adipiscing at in tellus integer feugiat. Eu lobortis elementum nibh tellus molestie nunc. Sagittis purus sit amet volutpat. Facilisis leo vel fringilla est. Luctus venenatis lectus magna fringilla urna. Faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae. Amet consectetur adipiscing elit ut aliquam. Commodo ullamcorper a lacus vestibulum sed arcu non odio. Gravida cum sociis natoque penatibus et magnis dis. Sit amet venenatis urna cursus eget nunc scelerisque. Mollis aliquam ut porttitor leo a diam. Vestibulum mattis ullamcorper velit sed. Tellus rutrum tellus pellentesque eu tincidunt.</h1>
<h1>{text}</h1>

First one respects defined width as aqua:
enter image description here

Second one doesn’t respect defined width and destroys the whole layout:
enter image description here

text is updated by JavaScript after both of headlines are rendered. At render time the length of h1 content is zero (text = '') and heading renders correctly. I assume after JS starts to change it the h1 doesn’t know the actual length of content and it can’t compute the wrap correctly.

I tried to give width and max-width properties to the second h1. There were no changes in behaviour but I confirmed it goes out of width as red:
enter image description here

What should be the correct approach that second headline respects the width?