1

i search for "how to replace selected text in div", and i found but it dosent work for html tags, how can i replace text and do a bold text for example? this is the code that i found:

function wrap(tag) {
    var sel, range;

    if (window.getSelection) {
        sel = window.getSelection();

        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            selectedText = range.toString();
            range.deleteContents();
            range.insertNode(document.createTextNode('<jhjhgjhjhgj>' + selectedText + '</' + tag + '>'));
        }
    }
    else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        selectedText = document.selection.createRange().text + "";
        range.text = '<' + tag + '>' + selectedText + '</' + tag + '>';
    }

}
blex
  • 24,941
  • 5
  • 39
  • 72
Kaki Baleven
  • 355
  • 3
  • 7
  • 19
  • If you wouldn't mind using jQuery you could do the following: http://stackoverflow.com/questions/918792/use-jquery-to-change-an-html-tag – Nick Faasen Mar 12 '15 at 19:50

1 Answers1

0

http://api.jquery.com/contents/

With jQuery you can call for the contents of a particular node. Once you have it you can replace your targeted substring.

  • i think you both dont understand me. i need to wrap the select text in div with for example... – Kaki Baleven Mar 12 '15 at 20:36
  • Have you tried assigning the `div` contents to a variable? Then you can append your `` tags to the ends, and replace the whole thing with your updated string. – anEffingChamp Mar 19 '15 at 16:06
  • its possible , but if i get the content of my div from innerHTML for example, i dont know what is the select text... – Kaki Baleven Apr 01 '15 at 12:34