skip to Main Content

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.

2

Answers


  1. This script selects all the captions on the page using document.querySelectorAll('.caption'), loops through each caption, and then splits the text content of the caption into title and subtitle using the colon separator. It then creates a new HTML string with the title and subtitle wrapped in tags with appropriate classes, and replaces the original caption HTML with the new HTML using caption.innerHTML.

    // Get all the captions
    var captions = document.querySelectorAll('.caption');
    
    // Loop through each caption
    captions.forEach(function(caption) {
      // Get the text content of the caption
      var captionText = caption.textContent;
    
      // Split the text into title and subtitle using the colon separator
      var titleSubtitleArray = captionText.split(':');
      var title = titleSubtitleArray[0];
      var subtitle = titleSubtitleArray[1].trim();
    
      // Replace the original caption HTML with the new HTML
      caption.innerHTML = '<span class="title">' + title + '</span><span class="subtitle">' + subtitle + '</span>';
    });
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search