How to wrap part of the text with spans using jQuery?
Asked Answered
C

2

5

Here is what I am trying to do

Fox<span>Rox</span>

before that

FoxRox

How do I wrap spans around Rox?

Cosette answered 4/5, 2012 at 4:0 Comment(1)
If you can tell us why do you need it and some more context we will able to help you more. Take is as an advise to further questions here.Louielouis
L
7

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>');
});​

Live DEMO

Louielouis answered 4/5, 2012 at 4:7 Comment(4)
I got Unexpected token ILLEGAL too :(Cosette
@Louielouis I'm getting some odd results - might be the fault of jsbin.Rondeau
@Louielouis Just tried everything in jsfiddle and it worked fine. Goodness, jsbin had me going crazy for a moment there.Rondeau
@user1374078 It was jsFiddle error, it's blocking you from doing things. Now I disabled it with a container. Try again pleaseLouielouis
R
5

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.

Rondeau answered 4/5, 2012 at 4:2 Comment(6)
I guess the hard thing is how to change the DOM.Louielouis
Please check my websites that I am working on right now, foxklld.site88.net. I pasted your code but it gives me some kind of error and also that I want to replace KllD with Rox you will see what I mean. So I want something like this 'FoxKllD'.replace(/(KllD)/, '<span>Rox</span>');. Also, On chrome console it said Unexpected token ILLEGAL.Cosette
@user1374078 But you want to replace it all throughout your document, right?Rondeau
I dont know anything about it. As long as it works it's fine for meCosette
@user1374078 I'm asking what you want. Do you want the script to search the entire website, and replace "K11D" where ever it is with "<span>Rox</span>"?Rondeau
@user1374078. So I added the relevant tags to your question. Please do it next time to make your question clearer.Louielouis

© 2022 - 2024 — McMap. All rights reserved.