0

how i can to find selected text in a div , in html

for example we have selected from 5 to 11 in this text :

     <div id="txt" >This is some <i> text </i> </div>

selected : is some ,

but in html is : id="txt

how to find this and replace between <p> or <span> that other tags to avoid loss of ?

excuse me for my bad english :)

talkhabi
  • 2,669
  • 3
  • 20
  • 29

1 Answers1

1

Demo: http://jsfiddle.net/dKaJ3/2/

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    alert(html);
}

Taken from: How to replace selected text with html in a contenteditable element?

Try to find things before you ask ;]

Community
  • 1
  • 1
Entity Black
  • 3,401
  • 2
  • 23
  • 38