Add item before / after selecting text

I am looking for a function that allows me to create an element before or after the selected text. Something like this javascript will replace the selection of all browsers , but to add some content before or after the selection instead of replacing it, for example the after() and before() methods of jQuery. Should I use any DOM selection method, if so, which one? Or is there something easier to accomplish?

+6
source share
2 answers

Here are a couple of features for this.

Real-time example: http://jsfiddle.net/hjfVw/

the code:

 var insertHtmlBeforeSelection, insertHtmlAfterSelection; (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("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node); } 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); })(); 
+10
source

In MSIE: collapse a given range and use pasteHTML to insert an element

Others: Also collapse a given Range and insert an element through insertNode


Both collapse methods take an optional argument, which determines where you want to collapse. If you want to put an element at the end, collapse to the end, otherwise to the beginning.

+2
source

Source: https://habr.com/ru/post/902478/


All Articles