Replacing text with a link in jQuery
I'm trying to replace a sm开发者_JAVA百科all 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! :)
You more than likely want the highlight plugin and just modify to wrap a link if you wish.
http://www.unwrongest.com/projects/highlight/
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.)
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()
精彩评论