I'm using contenteditable
div as an editor and sometimes I add some code. I need to wrab that code inside code
element.
to do that I made the next attempt.
Usage:
- add some text with line breaks.
- select that text.
- Click the button to wrap the selection.
The problem: when I wrap the selection it loses, unwantedly, all line breaks.
function wrapSelection(){
var selected = window.getSelection().toString();
if (selected != null) {
document.execCommand('insertHTML', false, code(selected));
};
}
var code = function (S) {
var str = "<code>" + S + "</code>";
return str;
};
#design_view {
border: 1px solid gray;
padding: 10px;
min-height: 200px;
font-size: 20px;
}
<button onClick="wrapSelection()">Select and Click</button>
<div contenteditable id="design_view">
</div>