jQuery replace string in element breaks content

33 Views Asked by At

I am building a jQuery-based tooltip-add-on. It works fine, so far.

terms is an Array which contains the words to be marked on the site. The words marked as stored in a span with styling.

On hover over the span, the tooltip is shown.

This is the function to mark the words:

function mark_terms(callback){

  terms.forEach(function(entry) {

    $('#tooltipped_area :not(script)').contents().filter(function() {

       return this.nodeType === 3;

     }).replaceWith(function() {

       regex = new RegExp('\\s\\b' + entry + '\\b\\s', "gi");
       
       return this.nodeValue.replace(regex, ' <span class="define" onMouseOver="show_tooltip(this.id)" onMouseOut="clear_timer()" id="' + entry + '">' + entry + '</span> ');

     });

      callback();

  });
}

It works fine so far. But I have two problems here:

  1. The site where this is running on, contains some code-blocks. E.g.:
#include <Morse.h>

With my method .. the string <Morse.h> is also be replaced... so that it is invisible after the replacement. I think because it turns out as a "html element" <Morse.h>

How can I fix this?


The second Problem is:

<span class="define" onMouseOver="show_tooltip(this.id)" onMouseOut="clear_timer()" id="' + entry + '">' + entry + '</span>

How can I temporarily safe the term which will be replaced, that it is the same as before afterwords.


>' + entry + '<

This turns the old word e.g. HelLoWoRld into HelloWorld. (HelloWorld is the "title" stored in the DB which is shown in the Tooltip)

I would need something like this:

var temp_word_that_will_be_replaced = HelLoWoRld;
>' + temp_word_that_will_be_replaced + '<

I have no idea.

0

There are 0 best solutions below