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/