3

I need to replace one pattern like that : "{12345,abcd}" in html of body but i woludn't lose the events of children. I have tried that code :

$("body").html($("body").html().replace(/[{]{1}([\d]+)[,]{1}(.*?)[}]{1}/g, "<span>Code:$1</span> - <span>Text:$2</span>"))

but that kill all events of elements. How i can do?

Ali
  • 56,466
  • 29
  • 168
  • 265
Emanuele Pavanello
  • 785
  • 1
  • 9
  • 22

3 Answers3

3

You have 3 options:

  1. Open the related view in your IDE, modify it and like a gentleman generate the desired markup. Modifying HTML using regex is a bad practice.

  2. Select only the descendant elements than can have that string and replace their textContent instead of the resetting entire body contents.

    $('.elements').text(function(_, oldText) {
        return oldText.replace('foo', 'bar');
    });
    
  3. Replace the body' contents and delegate all the events:

    $(document).on('event', 'element', fn);
    

    You can also replace the body' contents before binding event handlers. This of course won't break future event handlers.

Community
  • 1
  • 1
Ram
  • 143,282
  • 16
  • 168
  • 197
2

@BlackSeep That not work if I would do something like angularJs parser, I have solved fetching all text items and searching into for the regex. This is the solution for me :

$("body").find(":not(iframe)").addBack().contents().each(function() {
    if(this.nodeType == 3)
    {
        $(this).first().replaceWith( $(this).text().replace(/[{]{1}([\d]+)[,]{1}(.*?)[}]{1}/g, "<span class='translator' data-code='$1' data-text='$2'>$2</span>"));
    }
});

For information I had used this for have one mapper for webpages translation. Where i print "{id,text}" i replace that with one span and then I handle one special event for launch the translation of that box.

Emanuele Pavanello
  • 785
  • 1
  • 9
  • 22
0

this happens because html() method works with text (not dom elements) and text doesn't save event listeners, so u first read text, then do something with it (replace), then write it. In this situation you will loose as event listeners as they are attached to DOM objects (not to text) i think the best way is to go through all Dome tree , find all textNode DOM elements, and to do replace separately in each of them

Vlad Nikitin
  • 1,929
  • 15
  • 17