How to wrap part of the text with spans using jQuery?
-
05-06-2021 - |
Question
Here is what I am trying to do
Fox<span>Rox</span>
before that
FoxRox
How do I wrap spans around Rox
?
Solution
This will search you whole DOM and replace each Rox
with <span>Rox</span>
:
$(':contains("Rox")').html(function(index, oldHTML) {
return oldHTML.replace(/(Rox)/g, '<span>$&</span>');
});
OTHER TIPS
In this case, you could use the JavaScript replace()
method:
'FoxRox'.replace(/(Rox)/, '<span>$1</span>');
To replace this all through the document, you could try the following:
$(":contains('Rox')").html(function(i,o){
return o.replace(/(Rox)/g, '<span>$1</span>');
});
Note, if your term is not "Rox", you'll need to change it in the above script.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow