0

EDIT: I found a good solution in this post Remove highlight added to selected text using JavaScript?

I´m making a script to highlight texts. I´m using <span> tags. This part was easy but now I come across a problem. When highlighting includes different nodes I need to close the <span> tag before the parent close, and open again de <span> in the new node. Is not a very good explanation so I put an example:

    <body>

       <p id="0">Lorem ipsum</p>

       <div id="1">dolor sit amet</div>

    </body>

I select for highlighting :

ipsum</p><div id="1">dolor sit

Then I have to close <span> before </p> and open after <div> programatically. Any ideas how can I do it? I prefer to do all the script with pure JavaScript, but any help will be appreciated.

Here its my function to highlight:

function surroundSelection(element) {



            if (window.getSelection)
            {
                var sel = window.getSelection();
                if (sel.rangeCount)
                {
                    console.log (sel);

                    var range = sel.getRangeAt(0).cloneRange();



                    range.surroundContents(element);
                    sel.removeAllRanges();
                    sel.addRange(range);



                }
            }
        }

Where element will be the tag ( in my case <span>)

Here it is what I have, with still the problem of highlight different nodes http://jsfiddle.net/nacles/4L6d57bs/

Community
  • 1
  • 1
Nacles
  • 1
  • 2

1 Answers1

0

You have to start a different spam on every part of the code you, in your example:

<span>ipsum</span></p><div id="1"><span>dolor sit</span>

so for you, just put a span in the begining and then look for the end of the string or a '<' if the tag is opening like

then note that there is a nested tag block, if the tag is a close like

then you just put a closing span.

There are a lot of cases but i think is not very difficult.

Manjar
  • 3,159
  • 32
  • 44