Using jQuery or Javascript to enclose every character in a given string with an HTML tag

I am trying to create a function that can take a string of text and wrap each letter within that string with an HTML tag such as <i> or <span>.

Although I have made some progress, the current solution is not working as expected.

The issue I am facing is that I want to ensure that any existing <span> tags in the string are not replaced or altered. If there is already a <span> present, it should either maintain its original classes or add the "test_new" class alongside the existing "test" class.

var words = $("p").text().split("");
$("p").empty();
$.each(words, function(i, v) {
  $("p").append($("<span class='test_new'>").text(v));
});
span {
   border: 1px solid red;
}

span.test {
    border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>This is a <span class="test">test</span> string</p>

After running the code, the <span> element should have a blue border, indicating that it has retained any original classes during the conversion process.

Your assistance on this matter would be greatly appreciated. Thank you!

Answer №1

In order to isolate text nodes, you must filter for them specifically (such as node.nodeType === Node, the example shown below). Additionally, to avoid wrapping white space, filtering based on that criteria is recommended (

node.nodeValue.trim() !== ""
, as demonstrated in the example).

jQuery's filter function enables you to accomplish this task.

I devised a function that envelops each letter of a text with your specified span tag using the standard map function.

Finally, by iterating through each text node and utilizing jQuery's replaceWith function along with our newly developed wrapChars function, it becomes possible to enclose all characters within all text nodes.

$('p').contents()
      .filter((i, node) => node.nodeType === Node.TEXT_NODE && node.nodeValue.trim() !== "")
      .each((i, textNode) => $(textNode).replaceWith(wrapChars($(textNode).text())));

function wrapChars(text) {
  return [...text].map((c) => `<span class="test_new">${c}</span>`).join('');
}
span.test_new {
    border: 1px solid red;
}

span.test {
    border: 1px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is a <span class="test">test</span> string</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

Automatically populate the next dropdown menu depending on the answer provided in the previous field

Can you help guide me in the right direction with 2 questions I have? If the answer to the first question is 1, then I would like the following answer to automatically be populated as Yes. Please assist me! <div class="field"> <!-- Number of Em ...

PHP & Ajax integration for uploading files via a Bootstrap modal dialog

After exploring numerous posts for a solution to my issue without success, I felt the need to seek assistance specific to my problem here. Currently, I am using form elements in a modal. All the form elements successfully submit through my Ajax and store ...

Struggling to repair the unresponsive on-click event even after thorough debugging efforts

i am working on a project where i have to create a datatable, but I am facing an issue with the edit event not firing on click. Even after debugging, it is not pointing towards any error. function GetLoginData() { $.ajax({ url: '/LoginMas ...

Techniques for transferring PHP print_r arrays to Javascript

Array ( [0] => Array ( [sno] => 1 [name] => Sivamani [contact] => 750241378 [$city] => Madurai ) ) Array ( [1] => Array ( [sno] => 2 ...

I prefer not to have my preceding component re-rendered in React

I'm currently working on developing a user interface for a search engine using elasticsearch within React. One issue I'm facing is with the Pagination technique - when a user clicks on a result and then navigates back to the list of results, it r ...

Creating a cron job that can be rescheduled using Node.js

I am utilizing the node-schedule package from GitHub to create cron jobs. While I have successfully created a basic scheduler, my goal is to make it reschedulable. Within my application, users can initiate tasks for specific dates. This can be easily achi ...

Easily transfer a Jquery array to a Rails controller action!

I'm struggling to understand how to send a query in JSON format to a Rails controller#action. Here's what I have: var myarray = []; ( with values ) This is the controller action I want to post to: def process end I've searched everywher ...

Exploring the wonders of math in Angular with ng-repeat

Exploring the realm of mathematics within an angular expression, let's consider a scenario where a user can either have credit on the site or receive a percentage discount. Below is the code snippet in question: <div ng-repeat="item in NewArrivals ...

Struggling to connect HTML with CSS in Hugo

I am experimenting with a pre-fabricated theme in Hugo and incorporating some Bootstrap codes. I want to change the color of all links when displayed or hovered over. Despite searching extensively, I have been unable to achieve this through the use of CSS ...

Anomalies observed in label transition while in active state for input field

Can you explain why there is a gap in the label when it's positioned at left:0? I'm aiming to achieve a UI similar to Material design but struggling with label positioning. I've experimented with using translateY(-6px), however, this method ...

Attach a click event handler to a D3 element

Upon loading the page, the nodeClick() method is called without any clicking action. How can I adjust it so that the nodeClick() function is only triggered when I click on the element? Here is the code snippet: var node = svg.selectAll(".node") .on( ...

What could be causing my if-else statement to malfunction in JavaScript?

I'm working on a form where certain conditions need to be met based on the selected order type. For instance, if a market order is chosen, the stop price and limit price should default to zero and become read-only fields. Similarly, selecting a limit ...

Discovering the specific style within an inspect-element and transferring it to a JavaScript file

As a novice in the realm of react/javascript, I encountered a situation where I successfully edited a specific style using the inspect element tool. However, despite my efforts, I struggled to locate the corresponding style within the Javascript file. Ha ...

Error: Attempting to update the value of 'ordersToDisplay' before it has been initialized in a re-render of React. This results in an Uncaught ReferenceError

Trying to dynamically update the document title to include the order number by clicking a button to display different numbers of orders from an array on the screen. The process involves importing a JSON file, filtering it based on user input, calculating ...

The code for the submit button functions properly in Firefox, but encounters issues in Internet Explorer

While this code functions correctly in Firefox, it fails to work in IE8. <a class="sub"> <input type="submit" a="" none;<="" display:=""> </a> Although the button appears on the page, it is not clickable in IE8. Can you help explain ...

Troubleshooting a Simple JavaScript Game: Mastermind Edition

Currently, I am working on a JavaScript version of the well-known board game "Mastermind". I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying ...

What steps do I need to take in order to successfully make a checkbox?

I am attempting to use Angularjs to set a checkbox to true. When saved, it should store an integer value (1 or 0) in my field. Below is the code snippet for the view: <input type="checkbox" ng-model="lis.SMSPromotion" id="SMSPromotion" ng-init="checke ...

Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Exploring different options for parsing HTML content and extracting text from strings that do not contain HTML/XML tags

When looking at this particular solution for stripping HTML tags from a string, the process involves passing the string to rvest::read_html() in order to generate an html_document object. Subsequently, this object is input into rvest::html_text() to obtai ...