How to handle unclosed tags in image captions

Is there any way to “clean” the output of an image caption? We have a site that uses an ACF gallery field that’s output via the L&L slider. If an editor adds a html tag to the image (eg: as a creative commons reference etc…) but fails to properly close it, it causes problems for the rest of the page.

Obviously in an ideal world there wouldn’t be errors, but a typo meant they used <a> instead of </a> to close it so we just want to try and add in a layer of protection against future errors.

This it the code we’re using

<Slider>
  <Loop acf_gallery=stadium_images>
    <Slide>
      <div class="image_slide">
        <img src="{Field url}" alt="{Field alt}">
        <div class="image_text">
          <Field alt />
          <If field=caption exists>
            <br>
            <em><Field caption  /></em>
          </If>
        </div>
      </div>
    </Slide>
  </Loop>
</Slider>

The browser itself often corrects such malformed HTML in certain situations, like automatically closing unclosed tags. You might be able to achieve it by replacing this:

<br>
<em><Field caption /></em>

…with…

<div style="font-style: italic">
  <Field caption />
</div>

The closing div might help let the browser know that any unclosed tags within should be closed.

Also, the em tag may be problematic depending on what’s inside of it, for example another div.

Thanks Eliot - wouldn’t the closing image_text div have the same affect though? Ie: the output is already within a div that gets closed within the loop output.

They shouldn’t be putting divs in the captions, but you never know so point taken on that as well.