iframe change selection

1.1k Views Asked by At

I'm creating a really simple rte and here is my problem, i can get the selected text in iframe(designmode=true) however i cannot change it.

html

<a onclick="change();">change</a>
<iframe id="textEditor"></iframe>

script file

function $(Str1){return document.getElementById(Str1);}
rte()
{
    var texteditor=$('texteditor');
    textEditor.document.designMode="on";
    textEditor.document.body.contentEditable="True";
    textEditor.document.open();
    textEditor.document.close();
    textEditor.focus();

}
function change()
{
    var userSelection,range;
    if (window.frames['textEditor'].getSelection)
    {
        userSelection=window.frames['textEditor'].getSelection();
    }
    else if(document.frames['textEditor'].selection)
    {
        userSelection=document.frames['textEditor'].selection.createRange();
    }
    if(userSelection.getRangeAt)
    {
        range=userSelection.getRangeAt(0);
    }
    else
    {
        range=document.frames['textEditor'].createRange();
        range.setStart(userSelection.anchorNode,userSelection.anchorOffset);
        range.setEnd(userSelection.focusNode,userSelection.focusOffset);
    }
    range="<div style='color:#f00;'>" + range + "</div>";
}
window.onload = rte();
2

There are 2 best solutions below

1
On

Could it be that the first line of the rte() function references 'texteditor' and not 'textEditor'?

0
On

I found a way to work it up, change function should be like that

function change()
    if(document.selection)
    {
        sText=textEditor.document.selection.createRange();
        sText.execCommand("createlink","","");
        temp=sText.parentElement().innerHTML;
        newNode=textEditor.document.createElement("h1");
        replacement=sText.parentElement().replaceNode(newNode);
        newNode.innerHTML=temp;
    }
    else if(document.getSelection)
    {
        sText=textEditor.window.getSelection();
        myTag=textEditor.document.createElement("div");
        myTag.setAttribute("class","bold");
        sText.getRangeAt(0).surroundContents(myTag);
    }
}