Change every occurrence of span class red to be a strike tag

I'm attempting to replace all span tags with the red class and their content with a strike tag. However, I've encountered an issue where it doesn't seem to be replacing the specific span tags as expected.

Below is the code snippet:

let str = `<span class="black">time on hire shall not commence before the first layday (local time) and should the Vessel not have been delivered on or before the canceling date (local time) at the port or place stated in </span><span class="green"><span class="red"> Sub-clause 2(a) the Charterers shall  </span></span><span class="black">have the option of cancelling this Charter Party at any time but not later than the day of the </span><span class="red">Vessel</span><span class="black">/</span><span class="red">ad;s</span><span class="green">n</span><span class="black">
            </span><span class="red">notice of delivery. 
            </span>`;
str = str.replace(/<span[^>]+?class="red".*?>([^<]+)<\/span>/g,`<strike>$1</strike>`);
console.log(str);

The problem lies in the fact that the code currently only replaces a single instance of the span class red. My goal is to replace all occurrences of spans with the red class with the strike tag.

The current output looks like this:

"<span class="black">time on hire shall not commence before the first layday (local time) and should the Vessel not have been delivered on or before the canceling date (local time) at the port or place stated in </span><span class="green"><span class='red'> Sub-clause 2(a) the Charterers shall  </span></span><span class="black">have the option of cancelling this Charter Party at any time but not later than the day of the </span><strike>Vessel</strike><span class="black">/</span><strike>ad;s</strike><span class="green">n</span><span class="black">
</span><strike>notice of delivery. 
</strike>"

Note: I will later remove all remaining tags to convert it into a string containing only the strike tag for the red span text, hence CSS cannot be used in this case.

Answer №1

To start, establish a container element using the createElement() method and insert your HTML string within.

From here, you have the ability to alter this element just like any other within the DOM.

const str = document.createElement("div");
str.innerHTML =`<span class="black">time on hire shall not commence before the first layday (local time) and should the Vessel not have been delivered on or before the canceling date (local time) at the port or place stated in </span><span class="green"><span class="red">Sub-clause 2(a) the Charterers shall  </span></span><span class="black">have the option of cancelling this Charter Party at any time but not later than the day of the </span><span class="red">Vessel</span><span class="black">/</span><span class="red">ad;s</span><span class="green">n</span><span class="black"></span><span class="red">notice of delivery.</span>`;

Array.from(str.querySelectorAll("span.red")).forEach((el) => {
  const strike = document.createElement("strike");
  strike.classList.add(el.classList);
  strike.innerHTML = el.innerHTML;
  el.parentNode.replaceChild(strike, el);
});

console.log(str);
console.log(str.innerHTML);
document.body.innerHTML = str.innerHTML;

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

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

locomotory mesh decentralized sorting

I am attempting to implement in-browser sorting for my flexigrid. Currently, the grid is displaying data from a static XML file exactly how I want it, but the table itself does not sort because it is working off of local data. While researching solutions, ...

What is causing setTimeout to not function as intended?

I'm having some trouble moving a <div id="box"> whenever my mouse hovers over it. Currently, the element only moves when I trigger the mouseover event on the div itself instead of when my mouse is actually hovering over it. document.getElements ...

Is it possible to utilize gulp to eliminate all require.js define([...]) wrappers throughout the codebase?

Is it possible to test my app without using require.js in order to assess the performance and file size if all files were concatenated into a single one? I'm contemplating using gulp to gather all *.js files in the app, running a gulp-replace to elim ...

A small computation

How can I modify this code to calculate the total price #ttc by multiplying #totalcout with #marge Currently, I am able to add amounts when checkboxes are clicked, but I am struggling with integrating the multiplication for calculating the Total Price (TT ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

Leveraging nested objects within React state

A React child cannot be an object. If you intended to render a collection of children, utilize an array Encountering the error mentioned above has left me puzzled regarding its restrictions. Below is the code where I am facing this issue. It includes an o ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

What is the most effective method for handling extremely large Long numbers in Ajax?

When it comes to Javascript, all numbers are represented as double-precision floating-point. This can result in a loss of precision when handling numbers that exceed the 64 bit Java Long datatype limit of 17 digits. For instance, a number like: 7143412520 ...

Is it possible to use multiple AJAX requests to automatically fill out form fields?

In my Backbone.js web application, there is a form with multiple dropdowns that need to be populated with data fetched from an API. Since all the application logic resides on the client side due to using Backbone.js, I want to avoid populating these dropd ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Is there a way to efficiently manage multiple modules in AngularJS? I've put in a lot of effort, but while one module is functioning properly, the

angular .module('ApplicationOne',[]) .controller('myControllerOne', function($scope){ $scope.name = "Luther"; $scope.fname = "Martin"; $scope.ed = "B.TECH"; }); angular .module('App2&apos ...

Is there a way to efficiently display more than 10 data items at a time using the FlatList component in react-native?

Here is the data I am working with: singlePost?.Comments = [ 0: {id: 82, content: "Parent1", responseTo: null} 1: {id: 83, content: "Child1", responseTo: 82} 2: {id: 84, content: "Parent2", response ...

Tips for properly formatting the sort_by parameter in Cloudinary to avoid errors

Greetings to the helpful stack overflow community, I have encountered an issue with fetching images from cloudinary via a post request. Everything works fine until I include the sort_by parameter in the URL. This results in an error related to the format ...

Creating a Copy of an Object in JavaScript that Automatically Updates When the Original is Changed

I am in the process of developing a planner/calendar website with a repeat feature. var chain = _.chain(state.items).filter({'id': 1}).head().value(); console.log(chain); After filtering one object, I am wondering how to create a duplicate of c ...

Discover the process of loading one controller from another controller in Angular JS

Is it possible to load an entire controller1 from a different controller2, not just a function? ...

I'm seeking guidance on how to delete a specific ul li element by its id after making an ajax request to delete a corresponding row in MySQL database. I'm unsure about the correct placement for the jQuery

I have created an app that displays a list of income items. Each item is contained within an li element with a unique id, along with the item description and a small trash icon. Currently, I have implemented code that triggers an AJAX call when the user cl ...