views:

72

answers:

3

I'm trying to replace a small part of text in a large HTML document with my own element which I create on the fly.

The text may be a huge bulk of text, html, images, what-ever, and what I want is to find the first (or all) the position of a certain string, and replace it with an element that I create using $('< span>').

Using simple text.replace('the string', $('< span>')); doesn't do the trick (I'm left with [object Object] and not the actual < span> that I want.

The reason I don't just inject direct HTML is because I want to retain all the binds that are related to the object I'm creating. and doing a replace with a custom ID, and then attaching binds to the ID after the HTML has been altered, seems a bit dirty.

Thanks for the help! :)

+1  A: 

It's not that easy. Once you've picked up text() you've just got a simple string with no element node information, so doing replacements on it won't change the HTML DOM at all.

What you have to do is is search each Text node inside the tree one by one. And sadly jQuery doesn't provide much help for dealing with Text nodes.

You can use the findText function from this question. This usage would replace each ‘the string’ with an empty <span>:

findText(document.body, /the string/g, function(node, match) {
    var span= document.createElement('span');
    node.splitText(match.index+match[0].length);
    node.data= node.data.slice(0, match.index);
    node.parentNode.insertBefore(span, node.nextSibling);
});

(If you need to find text across different text nodes and elements, that's a much more complicated proposition.)

bobince
+1  A: 

You more than likely want the highlight plugin and just modify to wrap a link if you wish.

http://www.unwrongest.com/projects/highlight/

RobertPitt
Thanks, this is exactly what I had in mind, and actually using the same technique I wanted to avoid (splitting text, adding the object, adding the rest of the text).Thanks :)
Eli
Thought as much, Glad i could help.
RobertPitt
+1  A: 

For a simple solution

text.replace('the string', '<span></span>');

If you need a more elaborated element, you have to append the element on the position you want.

$("<span/>").appendTo(element);

As in your example, it is replacing the text with object.toString()

BrunoLM
also if you want to replace all strings that much your string not just first occurence then you need to specify global variable like text.replace('the string', '<span></span>', 'g');
Ayaz Alavi
sorry I mean just global not global variable.
Ayaz Alavi