Using innerHTML to replaceAll also modifies characters within the tags

I created a custom function to emphasize specific strings within a text by surrounding them with span tags and updating the content using the innerHTML property of the targeted element.

However, I encountered an issue while working with innerHTML instead of innerText. If the string to be replaced contains a character that is part of the span tag, it also gets replaced, resulting in a messy output.

Let me illustrate this problem with an example showcasing my function:

const strings = ['e', 'a'];
const pElement = document.querySelector('p');

function highlight(strings) {
  var highlightedText = pElement.innerText
  strings.forEach(element => {
    if (pElement.innerHTML.includes(`<span class="span">${element.charAt(0)}</span>`) && element.length > 1)
      highlightedText = highlightedText.replaceAll(`<span class="highlight">${element.charAt(0)}</span>`, element)
    //in case string element from array is longer than 1, so not important in this example
    if (pElement.innerText.includes(element))
      highlightedText = highlightedText.replaceAll(element, `<span class="highlight">${element}</span>`)
  });
  pElement.innerHTML = highlightedText
}

highlight(strings)
.highlight {
  background-color: red
}
<p>Lorem ipsum dolor sit amet</p>

As demonstrated above, when running the function, the output becomes:

Loran class="highlight">ean>m ipsum dolor sit aman class="highlight">ean>t
, due to the unintended replacement of characters within the span tags.

If anyone has a suggestion on how to only update the characters within the text without affecting the HTML elements, I would greatly appreciate it.

Answer №1

If you want to achieve this, you can separate the innerText into an array and then loop through the array to replace the identified elements with the desired HTML. Finally, join the array back together and update the HTML in the document object model.

For instance:

const characters = ['e', 'a'];
const pElement = document.querySelector('p');

function highlight(characters) {
  const updatedArr = pElement.innerText.split('').map(el => characters.includes(el) ? `<span class="highlight">${el}</span>` : el);
  
  pElement.innerHTML = updatedArr.join('');
}

highlight(characters)
.highlight {
  background-color: red;
}
<p>Lorem ipsum dolor sit amet</p>

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

Alter the color scheme of Fancybox's background

I am looking to create a transparent background color for Fancybox. The typical method involves using ".fancybox-skin" in CSS, however this will affect all fancyboxes and I require it to be unique. Therefore, the setting must be sent with wrapCSS. Fancyb ...

What is the method to display a group label using ng-table?

Does anyone have experience creating a group in ng-table? <div> <div ng-controller="ContractsController" style="position: relative;background:whitesmoke; border:1px solid lightgray; border-radius:5px; margin-top:0px; margin-bottom:5px; h ...

HTML border width is set to 100%, but there seems to be an issue with the responsive menu border and icon display

One issue I'm encountering with my website involves the border at the bottom of my navigation bar. Despite trying to adjust the box-sizing property to border-box, I still can't get it to display correctly. My goal is to have the border span 100% ...

A guide to converting variables into a JSON Object in Javascript

I am looking for a way to insert external variables into a JSON object. An example of what I want: var username = "zvincze"; And then, using that variable to inject it into a JSON object: var json = '{"username":"VARIABLE_GOES_HERE"}' var obj ...

Exploring TypeScript integration with Google Adsense featuring a personalized user interface

After following a tutorial on implementing Google AdSense in my Angular App, I successfully integrated it. Here's what I did: In the index.html file: <!-- Global site tag (gtag.js) - Google Analytics --> <script> (function(i,s,o,g,r,a,m ...

Styling text by reducing its size with CSS

Utilizing a CSS class to truncate text in the accordion header, which includes both a URL and plain text fields that need to be displayed on the same line. Desired Output: .../abc/xyz Count:42 Current output: .../abc/xyz Count:42/ (An odd slash is ...

Obtain the origin of the image using dots in Javascript

Sharing my experience with setting a background image using Javascript. Initially, I tried using two dots like this: .style.backgroundImage = "url('../images/image00.jpg')" However, it did not work as expected. So, I removed one dot: .style.ba ...

I continue to encounter an "Anticipated bracket" and "Surprising symbol" malfunction

I am currently working on a website using Wordpress and I am facing a problem with making the header full-screen while maintaining responsiveness. I want the code to only apply to desktop PCs and tablets, but I am encountering errors such as expected bra ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Integrating a neighborhood library with an Angular 5 Project

I want to have a local library that can reflect changes in the project using it. I have cloned the library from this link on my local machine: https://github.com/manfredsteyer/angular-oauth2-oidc Currently, I am navigating to the library directory and run ...

Getting the 3D Object Script in Three.js: A Step-by-Step Guide

I've been experimenting with three.js, specifically the Editor feature that allows you to attach scripts to 3D objects. In Unity 3D, accessing a script is as simple as using something like : targetGameObject.GetComponent (scriptName).targetVariable; ...

"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :) Screenshot: ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

Vue: Ensure user-triggered changes are detected in form input

Hello everyone, I recently started using Vue and I'm trying to achieve the following goal. I have a form with some data and a save button. Before the page fully loads, it needs to fetch data from the database and pre-fill the form. The save button sh ...

Is there a way to ensure that my AngularJS factory fetches HTTP data only once?

I have implemented a factory in my project to share data among multiple controllers. Here is the code for my factory: var szGetData = "some url that works"; myApp.factory('Data', function ($http) { var eventData = {}; eve ...

Checkbox change cannot be initiated

Using jQuery version 1.8.3, I am attempting to trigger a state change for each checkbox. The following code works when placed inside a click event: $("#btn_off").click(function(){ $( "tr td input" ).each(function( index ) { if ($(this).is(":ch ...

Using Node.js and Express, the CSS does not load due to route parameters

I'm currently working on a basic website project using Node.js, Express, and the EJS template engine. I've run into an issue where my external CSS files are not loading properly on routes that contain route parameters. Here's a snippet of my ...

Utilizing Kendo UI Jsonp in conjunction with a WordPress json plugin: A comprehensive

Issue at Hand: My goal is to modify a kendo UI data-binding example to work with my own jsonp request. Description of the Problem: Starting from a data-binding example here, I have created this jsfiddle that demonstrates the desired functionality. To a ...

Tips for redesigning your Bootstrap slider

Looking to update the carousel design for the previous and next buttons with a new look. I've attempted the following code: .carousel-control-prev { content: 'prev'; font-size: 55px; color: red; } <a class="carousel-control-next" ...