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!