You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML元素中搜索文本并高效获取Range对象?

需求与问题

我需要在HTML元素中搜索指定文本,并返回对应的Range对象,用于实现文本高亮、替换等功能(类似Grammarly的错误高亮)。

已尝试的方案及问题

1. 遍历元素子节点查找文本并构建Range

该方案存在两个核心问题:

  • 性能极差,耗时约350ms
  • 无法匹配到部分目标文本

相关实现代码:

const getRangeofText = (text) => {
  const children = document.activeElement;
  let finalNode;
  let parent = children;
  let i = 12;
  let isFound = false;
  while (parent.children.length > 0 && i > 0) {
    i--;
    console.log("I: ", i);
    console.log("traversing through: ", parent.childNodes);
    for (const item of Array.from(parent.childNodes)) {
      console.log("item: ", item);
      if (item.nodeType === 3 && item.textContent.includes(text)) {
        console.log("found in TEXT NODE");
        finalNode = item;
        isFound = true;
      }
      if (item.nodeType === 1 && item.textContent.includes(text)) {
        console.log("found in ELEMENT NODE");
        parent = item;
        finalNode = item;
        isFound = true;
      }
    }
  }

  console.log("final node: ", finalNode);

  const range = new Range();
  let startNode;
  let endNode;
  let arr = text.split(" ");
  let startWord = arr[0];
  let endWord = arr[arr.length - 1];
  if (finalNode) {
    if (finalNode.nodeType === 1) {
      let childNodes = finalNode.childNodes;
      for (const item of Array.from(childNodes)) {
        if (item.textContent.includes(startWord)) {
          startNode = item;
        }
        if (item.textContent.includes(endWord)) {
          endNode = item;
        }
      }

      range.setStart(startNode, 0);
      range.setEndAfter(endNode);
    } else {
      range.setStart(finalNode, 0);
      range.setEnd(finalNode, text.length);
    }

    window.getSelection().addRange(range);
  }
};

2. 使用Rangy库的findText()方法

调用该库的文本查找方法后,性能依然不理想,耗时约200ms。

求助

请问还有其他可行的实现方案吗?或者如何对现有函数进行性能优化与功能完善?

内容的提问来源于stack exchange,提问作者Abreham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:24:47