javascriptsquarespace

Use javascript to breakup a HTML div item via separator


I currently have a page with a gallery of images with captions on it.

<img>image1</img>
<div class="caption">IMAGE 1 TITLE: Subtitle</div>
<img>image2</img>
<div class="caption">IMAGE 2 TITLE: Subtitle</div>

and I would like to separate the Image Title from the Subtitle so that I can style them separately. They are always separated via a colon :. After replacement, the code should look something like

<img src="image1">
<div class="caption">
    <span class="title">IMAGE 1 TITLE</span>
    <span class="subtitle">Subtitle</span>
</div>
<img src="image2">
<div class="caption">
    <span class="title">IMAGE 2 TITLE</span>
    <span class="subtitle">Subtitle</span>
</div>

I do not have the ability to edit the HTML code, but I can do JS code injection and add custom CSS (this is a squarespace website).

I am looking for a script that would separate the text before and after the colon and wrap each of them in a class.


Solution

  • Grab the text, split it, and change the HTML to reflect your desired title/subtitle markup.

    document.querySelectorAll('.caption').forEach((caption) => {
      const [title, subtitle] = caption.textContent.trim().split(/\s*:\s*/);
      caption.innerHTML = `
        <span class="title">${title}</span>
        <span class="subtitle">${subtitle}</span>
      `;
    });
    .caption { color: blue; }
    
    .title { font-weight: bold; }
    .subtitle { font-style: italic; }
    
    .title:after { content: ':'; } /* optional */
    <img src="http://placekitten.com/100/40" alt="image1" />
    <div class="caption">IMAGE 1 TITLE: Subtitle</div>
    <img src="http://placekitten.com/80/60" alt="image2" />
    <div class="caption">IMAGE 2 TITLE: Subtitle</div>