views:

35

answers:

1

Hi, I have a function that reads the content of an element, replaces a word with a link and then rewrites the content back into the element, obviously this means that all events that where previously set are lost. Does anyone know of a function/method that could find and replace content of an element without loosing the events? Thanks.

Edit: Without using a library

Here is my current code that does not destroy the events but turns < for example into < so I can not append HTML. This is the closest I have got.

element.appendChild(document.createTextNode(content));

My original code worked but got rid of the events.

element.innerHTML += content;
+2  A: 

By using jQuery you could do it with the text() method

var str = $('#element-id').text();
str = yourReplaceFunction(str);
$('#element-id').text(str);

Edit:

Another option would the innerHTML property. It's not very elegant but works nevertheless.

var strElem = document.getElementById('element-id');
var str = strElem.innerHTML;
str = yourReplaceFunction(str);
strElem.innerHTML = str;

Edit2:

Yet another option would be to wrap the text you want to replace inside of a separate tag, for example <span>.

<div id="container">
   <a id="link-with-events">Link</a>
   <span id="replaceable">The Text Gets Replaced</span>
   <a id="more-links-with-events">Another Link</a>
</div>

Then you'd simply access and replace the contents of the span tag, leaving the surrounding elements untouched.

Saul
Well the problem is that I am writing a library so I don't want to be using jQuery, so do you know of any methods of find + replace that do not involve destroying the event listeners?
Wolfy87
Do you mean the events on the containing element? Or are you referring to events defined inside the content to be replaced?
Saul
I don't see what's so inelegant with using the `innerHTML` property.
Yi Jiang
I am currently using the innerHTML property, this is what destroys the events. I need to use DOM functions but I can't find one that would let me find and replace.
Wolfy87
@Yi Jiang: DOM is basically a tree so using tree operations makes more sense than "batch mode". But of course, that's not cast in stone, simply something I prefer.
Saul
Your third idea is the most useful. I think I am going to have to settle with that. Thanks for you time and help.
Wolfy87