contenteditable中,设置光标位置时,range.setStart报错,怎么办?

原div

    <div id='div'>
        <p>
            123456
            <br>
            abc
            <br>
        </p>
    </div>
        ```
要求:在a后面插入字符串xxxf,怎样是光标定位到xxxf后面

实现逻辑

const div = document.getElementById('div')
div.innerHTML = '

123456
abxxxfc

' // 代替插入字符串代码
const range = document.createRange()
range.setStart(div.children[0], 13) // 13是f的位置
执行报错
IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 13.

有解决了吗?怎么解决的,我也遇到了这个问题

为什么要用range,直接对字符串操作不就好了
通过id获取html内容
然后
str = str.slice(0, str.indexof('a')) + newStr + str.slice(str.indexof('a'));
用slice将字符串截成前后两截,然后中间拼上内容再用innerHTML放回去
代码手撸的可能有错,但是就是那个意思