Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an element at selected position in HTML document?

I want to insert an element(span,div etc) at the position determined by user selection of text in the document.

I was able to get the element on which selection is made. But I am not able to get the exact position where the selection is made.

For example:

<span>this is testing string for testing purpose</span>

In this, lets assume that user selected 2nd 'testing' word. I want it to be replaced like

<span>this is testing string for <b>testing</b> purpose</span>

How do i do it?

BTW: I know it is possible. Google Wave does it. I just dont know how to do it

like image 820
Rajesh Avatar asked Jul 29 '10 13:07

Rajesh


People also ask

How do you find the position of an element in HTML?

Use element. getBoundingClientRect() property to get the position of an element.

What is insert adjacent HTML?

insertAdjacentHTML() The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.

Is used to insert elements into document body?

To insert an element into the body tag: Create an element using the document. createElement() method.


1 Answers

This will do the job:

function replaceSelectionWithNode(node) {
    var range, html;
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.deleteContents();
        range.insertNode(node);
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        html = (node.nodeType == 3) ? node.data : node.outerHTML;
        range.pasteHTML(html);
    }
}

var el = document.createElement("b");
el.appendChild(document.createTextNode("testing"));
replaceSelectionWithNode(el);
like image 129
Tim Down Avatar answered Oct 17 '22 19:10

Tim Down