遍历Range对象中的元素并更改它们

时间:2015-05-26 11:03:23

标签: javascript dom

如何遍历Range对象中的元素并能够更改它们?

用例:

一个扩展,它应该是用户选择并在链接中包含一些文本出现(法律参考)。

要做到这一点,我们需要:

  1. 遍历Range对象中的所有元素
  2. 使用相同的文本替换某些文本节点的内容,但添加了链接。
  3. 我知道如何做第一步:

    var sel = document.getSelection();
    var range = sel.getRangeAt(0);
    var walker = document.createTreeWalker(range.cloneContents(), NodeFilter.SHOW_TEXT);
    var node;
    while (node = walker.nextNode()) {
      console.log(node);
      // we have a copy of an original text node here and can use a text of it
      // and can't change a text of an original node, just a text of copied one
    }
    

    我使用了上面的Range.cloneContents()函数,它使得文件片段来自Range对象的复制元素。可能有一种方法可以从Range对象中的原始元素创建文档片段吗?我还没有找到这样的功能......还有另外一个类似的功能 - Range.extractContents(),但它从文档中删除了元素。

0 个答案:

没有答案
相关问题