Tips for dynamically updating the formatting of a specific word within an HTML paragraph using code?

I am looking for a way to dynamically change the appearance of a specific word within an HTML paragraph


let textToFind = "testing"

let beforeNode = document.createElement('p');
let afterNode = document.createElement('p');

let highlightedSpan = document.createElement('span')
highlightedSpan.innerHTML = textToFind;
highlightedSpan.style.backgroundColor = "yellow"
let newPar = document.createElement('p');
newPar.appendChild(highlightedSpan);

document.querySelectorAll('p').forEach((par) => {
  let content = par.textContent;
  let startPos = content.indexOf(textToFind)
  console.log(startPos)
  if (startPos !== -1) {
    let firstPart = content.slice(0, startPos - 1)
    let thirdPart = content.slice(startPos + textToFind.length, content.length - 1)
    beforeNode.appendChild(document.createTextNode(firstPart))
    afterNode.appendChild(document.createTextNode(thirdPart))
    par.replaceWith(beforeNode, highlightedSpan, afterNode)
  }
})
<p> A complete text for testing purposes</p>

This currently gives me the following result:

https://i.sstatic.net/wK52a.png

However, I am seeking a more visually appealing approach as the current implementation splits the text into three lines. Is there a neater solution to changing the style of a single word in an HTML paragraph?

Answer №1

To easily replace a word with a wrapped version using regex, follow these steps:

const BODY = document.body;
BODY.innerHTML = BODY.innerHTML.replace('example', `<span>example</span>`);
span {
  background-color: orange;
}
<p> This is an example sentence for demonstration purposes</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

Submit a form containing multiple input fields along with JavaScript variables

I have successfully posted my form via ajax to PHP and retrieved values from inputs. Now, I would like to include a JavaScript variable in the ajax post as well. Here is the FORM section: <form action="new_alias.php" method="post" id="theForm"> ...

"Using jQuery $.extend will replace all content in the first object with the contents of the

Unfortunately, I am unable to provide a demonstration using anything other than code (no fiddle), but here is the issue at hand: Upon making an AJAX call to retrieve data from a JSON file and saving it to a variable, I then make another AJAX call to fetch ...

Hold on while utilizing Path (Puppeteer)

My current setup involves using Puppeteer 22.6.0 with NodeJS for web scraping purposes. I am facing a challenge where I need to pause the script until a specific h1 element becomes visible on the page. The tricky part is that there are multiple h1 elements ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

Clearing a database table in MySql by clicking an HTML button

I have a simple requirement for my website - I need to create a button that, when clicked, will truncate a database table. Unfortunately, I have been unable to do this successfully on my own. Can someone please help me with this task? Here is my attempt a ...

Divided screen showcasing one movable panel

I am currently working on a design where I have a container with a specified maximum height. Inside this container, there are two separate divs. One of these divs (the footer) has a fixed height of 55px, while the other is a scrollable div that adjusts its ...

What is the mechanism behind the jQuery ready function that enables its first parameter to transform into a jQuery object?

While browsing today, I came across this interesting code snippet: jQuery(document).ready(function($$){ console.log($$); }); It seems that $$ is recognized as the jQuery object itself. Typically, to achieve this, we would need to pass the jQuery varia ...

How can I create additional white space at the end of my webpage with CSS grid?

Looking for some help with CSS as a beginner here. I'm facing an issue where my CSS is creating excessive blank space at the bottom of my document, almost 60% of it. Could this be due to incorrect parent parameters or the children elements? This is m ...

Securing a REST API accessible through JavaScript by implementing authentication techniques due to the visibility of the public code

Inquiry: Need advice on securing an internal API intended for AJAX calls made within the website. I have developed a REST API in PHP 7.2 for use with client-side Javascript. Typically, I work on server-side applications where I can control access using a ...

The JQuery Slide feature seems to be malfunctioning when handling data retrieved from the database

I have set up a database with two tables, each containing three rows and connected by ID. The data in table_1 (questions) is linked to the corresponding responses in table_2 (answers) through this linkage. Recently, I attempted to incorporate a SLIDEUP/SL ...

Ways to perfectly align objects in a container without compromising the height of the parent element

Within my container div, I have two spans. An issue arises when I attempt to align the items to the center using align-items: center, as this causes the spans to lose their defined height and border-radius properties. My goal is to keep the heights and bor ...

XML, XTL, and HyperText Markup Language (HTML)

I am facing a challenge with transforming a list in an XML file into an HTML view using XSLT. The nesting of the lists is causing issues and the output is not meeting my requirements. XML: <book-part> <list id="ch4list2" list-type="simple"> & ...

Generating a compilation from an array in React JS

Having trouble creating an array to store my category links and display them on my website. However, I'm not seeing anything in my DOM. Any assistance would be greatly appreciated :) import React from "react"; import { SidebarCategory } from './ ...

Steps for making a webpack-bundled function accessible globally

I am currently working with a webpack-bundled TypeScript file that contains a function I need to access from the global scope. Here is an example of the code: // bundled.ts import * as Excel from 'exceljs'; import { saveAs } from 'file-save ...

What is the correct method in Rivets.js to fill in a placeholder in the image source attribute of an HTML element?

I have recently designed a page: <div id="mypage" data-role="page" data-theme="w"> <div id="header" data-role="header" class="ui-noboxshadow ui-header-fixed" data-position="fixed"> </div> <div data-role="content"> <p ...

Is there a way to showcase interactive HTML content similar to an ePub or eBook without the need to convert the HTML into ePub

Looking to enhance the mobile reading experience with a responsive design similar to popular ebook readers like Kindle or iBooks? Want to break long articles into full-screen sections for easy navigation on small devices? Consider using dynamic HTML to ada ...

I encountered an issue while trying to send data from a React.js application to PHP using Axios. However,

I am utilizing react.js, axios, and PHP to transmit data to a MySQL database Below is my react.js code snippet sendData(){ var data = new FormData(); data.append('name', 'jessie'); data.append('time', '12:00'); dat ...

DIV being obstructed by an IFRAME

I am facing an issue with my ASP.NET site where I have used an Ajax Control Toolkit Animation Extender to animate a div flying out, which contains a simple treeview. Upon selecting a node in the treeview, a protected sub is triggered, setting the source o ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

Using PHP to populate Highcharts with data through the use of json_encode

I've been grappling with integrating highcharts and json_encode using PHP for a few days now. I'm confident that my data is correctly formatted, yet the chart isn't updating as expected. The category data updates smoothly, and the series dat ...