<input type="button" value="Insert before" onmousedown="insertHtmlBeforeSelection('test')">
<input type="button" value="Insert after" onmousedown="insertHtmlAfterSelection('best')">
<div>
I'm looking for function which allows me to build some element before or after selected text. Something similar like this one javascript replace selection all browsers but for adding some content before or after selection instead of replacing it, like after() and before() jQuery methods. Should I use some DOM selection method, if yes which one? Or does exist something easier to carry it out?
</div>
JavaScript
var insertHtmlBeforeSelection, insertHtmlAfterSelection;
$(document).ready(function() {
(function() {
function createInserter(isBefore) {
return function(html) {
var sel, range, node;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
range.collapse(isBefore);
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement('span');
el.className = 'addwordselect';
el.setAttribute('data-word',html);
el.innerHTML = html;
console.log(el);
var frag = document.createDocumentFragment(), node, lastNode;
//while ( (node = el.firstChild) ) {
// lastNode = frag.appendChild(node);
//}
lastNode=frag.appendChild(el);
range.insertNode(frag);
}
} else if (document.selection && document.selection.createRange) {
// IE < 9
range = document.selection.createRange();
range.collapse(isBefore);
range.pasteHTML(html);
}
}
}
insertHtmlBeforeSelection = createInserter(true);
insertHtmlAfterSelection = createInserter(false);
})();
$(document).on('dblclick', "body", function(e) {
//var Selected = window.getSelection().toString();
console.log('test');
insertHtmlAfterSelection();
});
insertHtmlBeforeSelection = createInserter(true);
insertHtmlAfterSelection = createInserter(false);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.