Utilize JavaScript to split an HTML div section using a delimiter

On my current webpage, I have a gallery of images accompanied by captions.

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

I am interested in rearranging the Image Title and Subtitle within each caption so that I can style them individually. Each pair is currently divided by a colon :. Following this modification, the code should display as follows:

<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>

Although I cannot directly edit the HTML code, I do have the ability to inject JS code and insert custom CSS (as it is a squarespace website).

I am seeking a script that can effectively separate the text before and after the colon in each caption and then enclose them within respective classes.

Answer №1

Take the text, separate it into parts, and update the HTML to show your preferred title/subtitle formatting.

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>

Answer №2

This code snippet locates all the captions present on the webpage by using

document.querySelectorAll('.caption')
. It then proceeds to iterate through each caption, where it divides the text content of the caption into a title and subtitle by utilizing a colon as the separator. Afterwards, it constructs a fresh HTML string containing the title and subtitle encapsulated within appropriate classes, subsequently substituting the original caption HTML with this new HTML via caption.innerHTML.

// Gather all the captions
var captions = document.querySelectorAll('.caption');

// Iterate through each caption
captions.forEach(function(caption) {
  // Obtain 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 initial caption HTML with the updated HTML
  caption.innerHTML = '<span class="title">' + title + '</span><span class="subtitle">' + subtitle + '</span>';
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

Try opening a fresh page instead of displaying a pop-up that says "your message has been sent"

I am currently utilizing the "Agency" one-page Bootstrap template. Upon successful form submission and email sending, a popup message is displayed. My preference is to have a new page open instead of the popup. $(function() { $("input,textarea").jqBoot ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Convert JSON object to a string representation

I am attempting to print a JSON object in string format. (I actually retrieved these data values from Ruby code var data = '<%=[@pro {|c| {x:c.x, y:c.y}}].to_json%>') When printing the data variable, I noticed that the values contain & ...

Utilizing the state as a condition within the useEffect to update the component

Is there a way to automatically hide the mobile menu when the URL changes in ReactRouter? I have noticed that I get a warning for not tracking mobileOpen as a dependency, but strangely the code still works fine. const Navbar: React.FC<Props> = props ...

Unusual escape_javascript quirk witnessed in Ruby on Rails

Once the ajax method is called, the escape_javascript function starts outputting </div> </div> </div> for each rendered item. Despite thoroughly checking all closing tags multiple times, I can't seem to identify any errors. Could thi ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

Insert a Facebook like button within a designated div

Can anyone figure out why the Facebook button isn't functioning properly? ---- ...

How can I display color without using Winston's color formatter in text?

Currently, I am in the process of developing a logging module using winston as the selected logging framework. It offers the convenience of specifying colors, which is particularly appealing when utilizing the Console transport. However, if I were to defin ...

Can you determine the measurements of the combined image's height and width?

Here is my code: for(var i=1;i<10;i++){ $('#vid_c_'+i).append('<div class="move_2" id="vd'+i+'"></div>'); $('#vd'+i).append('<img class="class" id="id_'+i+'" src="'+_m[i ...

How can Typescript be leveraged to enforce a generic constraint on an interface?

I have defined 2 interface declarations : interface IStore { } interface AnotherInterface { a: number; } Also, there are 2 classes which implement each interface: class StoreImplementation implements IStore { } class AnotherImplementation implement ...

Tips on incorporating a past random selection into an RPG lifepath generator's current random selection process

Currently, I am in the process of creating a JavaScript version of a basic "life path generator" commonly seen in pen and paper RPGs. The generators I have been working on are inspired by the structure provided at this link: However, I am encountering dif ...

The jQuery selector is unable to locate the IMG element using its unique ID

I'm experiencing an issue with a webpage that includes the following code snippet: <img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01. ...

Angular retrieving a document collection from Firebase based on a specific field

I am trying to retrieve collection data based on the UserId field. retrieveData(){ const data$ = this.firestore.collection(this.trackerCollection,ref=> ref.where('UserId','==',"WrKDk0XSNjU20FI0EVRvADzvNHz1")).snapshotCha ...

What is the significance of the error message '[WDS] Disconnected!' in the context of using webpack and Vue.js?

Currently, I am engaged in a Django project that utilizes Vue.js for the frontend. Whenever I refresh the page, I encounter the "[WDS] Disconnected!" error. Despite the website's full functionality and absence of issues, this error appears every time ...

Javascript troubleshooting: Confusion with Radiobuttons and Checkboxes 'checked' status

My Javascript code utilizes JQuery to generate quizzes with free text, radio buttons (single choice), and check boxes (multiple choice) questions. These quizzes are created using a web interface styled with Zurb - Foundation and serialized in JSON format. ...

I am facing difficulty importing emotion js style using dynamic variables

I recently designed a webpage that has the following appearance: https://i.stack.imgur.com/AnIXl.jpg Here is the code from my _app.tsx file: import '../styles/globals.css' import type { AppProps } from 'next/app' import { createTheme ...

Encountering a Jquery TypeError while trying to update the content on

I am currently working on a project where I aim to create a Java Spring application that functions as follows: upon receiving a GET request, the application sends an HTML page with a form. When the form button is clicked, a POST request containing XML cont ...