如何在替换id上创建范围?

时间:2017-05-27 14:23:51

标签: javascript jquery html

我有id div包含文本然后我更改其内容并替换为duplicate,但在此操作后我无法创建范围。有错误:

  

未捕获DOMException:无法执行'surroundContents'   'Range':容器节点是一个分离的字符数据节点;没有   父节点可以插入。

如何替换innerHTML以便我能够创建范围?[在此输入链接描述] [1]

var dupl = "";
function Selection()
{
        if(dupl == "") { dupl = document.getElementById('content').innerHTML; }
        
        var sel = window.getSelection();
        var anchor = sel.anchorNode;
        var anchoroffset = sel.anchorOffset;
        var focus = sel.focusNode;
        var focusoffset = sel.focusOffset;
            anchoroffset=anchoroffset+3;
            focusoffset= focusoffset +3;

       $("#content").html(dupl); 
       
       var range = document.createRange();
       range.setStart(anchor, anchoroffset); 
       range.setEnd(focus, focusoffset); 
       var newNode = document.createElement("b");
       range.surroundContents(newNode);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" onmouseup="Selection()">
<br>Hello fg hfg hfg hfg
<br>World! hfg hfg fg 
<br>
<a href="#">Here is your dream</a>
</div>

0 个答案:

没有答案