【问题标题】:How can I get all text node in document fragment?如何获取文档片段中的所有文本节点?
【发布时间】:2013-11-22 00:42:48
【问题描述】:

我得到用户选择的文本:

var selection = window.getSelection();
var selectRange = selection.getRangeAt(0);

var content = selectRange.cloneContents(); // DocumentFragment

如何在DocumentFragment 内容中获取textNode

【问题讨论】:

    标签: javascript textnode documentfragment


    【解决方案1】:

    使用textContent

    var selection = window.getSelection();
    var selectRange = selection.getRangeAt(0);
    var content = selectRange.cloneContents(); // DocumentFragment
    var text = content.textContent;
    

    【讨论】:

    • 旧消息,但 textContent 给你一个字符串,而不是一个 Node 数组。
    【解决方案2】:

    过滤fragment.childNodes获取文本节点:

    const selection = window.getSelection();
    const selectRange = selection.getRangeAt(0);
    const fragment = selectRange.cloneContents(); // DocumentFragment
    // Get the child nodes and filter them to only include text nodes
    const textNodes = Array.from(fragment.childNodes).filter(child => child.nodeName === "#text");
    

    【讨论】:

      【解决方案3】:

      结合一些技巧,很容易从任何容器节点(在本例中为 片段)中提取 文本节点。问题的fragment部分与提取部分无关。

      获取容器的所有子元素,使用扩展运算符 ... 将它们转换为“真实”数组,因此可以使用 filter。也可以跳过这部分,因为 HTMLCollection 确实支持forEach,因此可以在其中填充一个空数组。

      注意Node.TEXT_NODE3 的DOM 常量

      // create a demo fragment with some HTML mix of text nodes & elements
      var frag = document.createRange().createContextualFragment("<a>1</a> 2 <b>3</b> 4.");
      
      // now the work begins: get only the text nodes from the fragment
      var textNodes = [...frag.childNodes].filter(node => node.nodeType == Node.TEXT_NODE)
      
      // print the text nodes as an array
      console.log( textNodes.map(node => node.textContent) )

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-08
        • 2019-09-18
        相关资源
        最近更新 更多