Tips for excluding HTML tags within childNodes while performing a string.replace() using innerHTML

I am working on a project to enhance readability by replacing each word in a document's P tags with a span element. The code I have works well for the first case, but subsequent replacements start to mess up the HTML structure of the P tag. Here is an image of the issue

I'm wondering if my approach needs adjusting or if there is a way to only modify the innerHTML between the tags?

const runBionic = (node: ChildNode, paragraph: HTMLElement):HTMLElement => {
if (node.textContent === null) return paragraph;
const originalWords:string[] = node.textContent.split(" ");
const filteredWords: string[] = originalWords.filter(word => word!=="" && word !== "\n");
console.log("Filtered words: ", filteredWords);
//replace each word with a span element
filteredWords.forEach(word => {
    const modifiedWord = `<span style='font-weight: bold;'>${word}</span>`;
    console.log("REPLACING ", word, "WITH ", modifiedWord);
    paragraph.innerHTML = paragraph.innerHTML.replaceAll(word,modifiedWord);
});
return paragraph;};

My ultimate goal is to create a chrome extension that highlights the first half of characters of any word on a web page to assist dyslexic individuals in reading faster. You can find the complete repository on github for more information.

Answer №1

After some experimenting, I decided to replace the entire TextNode with a new span element instead. This approach allows me to prepare the entire element and then add it to its parent without requiring any regex operations...

const replaceNode = (node: ChildNode)=>{
if (node.textContent === null) return node;
const newChild = document.createElement("span");
const words: string[] = node.textContent.split(" ").filter(word => word!=="" && word !== "\n");
const HTMLstring: string = createSpans(words);
newChild.innerHTML = HTMLstring;
return newChild;};

const createSpans = (words : string[]) : string=>{
let HTMLstring = "";
words.forEach(word =>{
    const span = `<span> ${word} </span>`;
    HTMLstring += span;
});
return HTMLstring;};

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

The AJAX validation process fails to run prior to the execution of the login PHP script

My attempt to implement AJAX for form validation is not successful and I'm unsure why. Despite my efforts, the form still redirects to login_action.php instead of performing the AJAX validation as intended. I have designed a modal login form and wish ...

Ways to exclude specific index values from a loop

My challenge involves working with arrays, specifically y: var y = [1, 2, 3, 4]; I need to iterate through this array while excluding certain indexes that are stored in another array. var x = [1, 3]; Essentially, I want to output each number from array ...

Cycle through items and switch states using classList in JavaScript

Instructions: Utilize javascript and the classList property to change which elements have the .highlight class. Iterate through all the <li> elements and toggle the .highlight class on each one. Do not make any changes to the HTML and CSS. Your end ...

Unable to retrieve values using any = {} in TypeScript Angular 8

import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ selector: 'app-home', templat ...

Establish a default value for ng2-datepicker

Has anyone figured out how to set an initial value for the ng2-datepicker when using it for available date and date expires? I want the initial value of dateAvailable to be today's date and the initial value of dateExpires to be 2099-12-31. <label ...

Using Filters in VueJs

I am currently working on creating a small Vue.js 2.0 application where I am utilizing the v-select component from here. The data format that I am dealing with looks something like this: { "model": [ { "id":1, ...

VS code is showing the directory listing instead of serving the HTML file

Recently, I attempted to use nodejs to serve the Disp.html file by following a code snippet from a tutorial I found on YouTube. const http = require("http"); const fs = require("fs"); const fileContent = fs.readFileSync("Disp.html& ...

Is it possible for me to display a particular section of a webpage by utilizing document.getElementById(href)?

Is it possible to retrieve a specific part of a content page to display in a popup box? Let's say we have a page called "content page" with the following structure: <body> <p id="part1">Tread ... inch. </p> <p id="part2">Tr ...

Determine the return type based on the input parameter and a mapping strategy

I am encountering an issue with the inferred returnType of the following types. The problem lies in the cityAttractions type, where it should ideally have a type error in its return statement for returning a string instead of an array of strings. Playgrou ...

Encountering problems with Highcharts zoom feature following the update to jQuery 1.8

My application uses Highcharts 2.2.5 to create various area and bar charts. After upgrading my app to jQuery 1.8, I conducted tests on all my charts. Everything seemed fine until I tried zooming in on an area chart. Suddenly, I started getting numerous Ja ...

What steps do I need to take to build this jump page?

Disclaimer: I have very little experience with coding. As a self-taught graphic designer, I have only managed to create a simple page that helps me store common phrases I use frequently throughout the day. It was quite a challenge for me. I am currently w ...

Sending variable from JavaScript via AJAX to PHP results in an undefined variable

My goal is to pass the variable rating_index to my PHP code and then send it to the database. Although the actual code for rating_index is quite long, I can confirm that right before the AJAX call, I console.log(rating_index) and it displays an integer val ...

How to connect multiple HTTP requests using observables in Angular 7

Is there a more efficient way to remove an alert only if it is not assigned to any user? Currently, I am checking my users list and filtering out the users who have this alert assigned using observables. But I wonder if there is a better approach to achi ...

Node.JS AJAX request with no data payload

Encountering an issue where no data is being received on the server side from an AJAX request because the req.body is empty (console logs it as {}). script.js: $("#button").click(function(){ var number = $("#number").val(); $.ajax({ ...

Ways to design each element in React

I'm currently working on a React code that involves CSS for Scrolling functionality. When I try to use props.children.map, I encounter an error saying "TypeError: props.children.map is not a function". Since I am in the process of learning React.js, t ...

How can you achieve div scrolling in React by simply dragging the mouse?

I'm currently exploring options for scrolling through a div using mouse drag, but I haven't come across anything particularly helpful. Specifically, I'm trying to replicate the functionality found in Trello where you can horizontally scroll ...

Unable to retrieve a random element from an array in Angular 10

I'm attempting to shuffle items (cards that have English words) from a flashCards array, so that each card can appear randomly when the user reloads the page. I tried using the Math.floor(Math.random()) function, but it's not working. How can I r ...

Is it possible to delete a route if the .remove function is not available?

Hey there, I'm having an issue with a route I created to delete a product. Every time I try to run it, I'm getting an error message that says .remove is not a function. I've been searching for a solution but haven't been able to fix it. ...

Material-UI - TypeScript - Autocomplete utilizing getOptionLabel and renderOption for optimized selection functionality

I am attempting to showcase member and company using MUI Autocomplete. I have an array called suggestion that contains the options to display. [ { "__typename": "Member", "id": "ckwa91sfy0sd241b4l8rek ...

How come this javascript/jQuery code is unable to properly submit the HTML form?

Having some trouble with submitting an HTML form using Javascript/jQuery. It doesn't seem to be working as expected. Here is my HTML form: <form class="navbar-form navbar-right" role="form" id="loginForm" action="login.php"> <div class= ...