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
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 usingcaption.innerHTML
.Grab the text, split it, and change the HTML to reflect your desired title/subtitle markup.