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

如何修改JavaScript代码实现仅高亮匹配文本而非全部文本?

解决仅高亮匹配文本的问题

修改后的完整代码

const buttonEl = `<button>
  <span>
    Icon
  </span>
  Text
</button>
`;

document.body.innerHTML = buttonEl;

const foundButtonEl = document.querySelector("button");
const elements = [];

elements.push(foundButtonEl);

addHighlight(elements, "T");

function addHighlight(elements, text) {
  elements.forEach((element) => {
    // 仅搜索当前元素下的文本节点,而非整个body
    const textNodes = getTextNodes(element);
    textNodes.forEach(node => {
      const nodeText = node.textContent;
      const matchIndex = nodeText.indexOf(text);
      // 跳过不包含匹配文本的节点
      if (matchIndex === -1) return;

      // 拆分文本为三部分:匹配前、匹配内容、匹配后
      const beforeText = nodeText.slice(0, matchIndex);
      const matchText = nodeText.slice(matchIndex, matchIndex + text.length);
      const afterText = nodeText.slice(matchIndex + text.length);

      // 创建mark元素包裹匹配文本
      const markElement = document.createElement('mark');
      markElement.textContent = matchText;

      // 按顺序插入新节点并删除原文本节点
      node.parentNode.insertBefore(document.createTextNode(beforeText), node);
      node.parentNode.insertBefore(markElement, node);
      node.parentNode.insertBefore(document.createTextNode(afterText), node);
      node.parentNode.removeChild(node);
    });
  });
}

function getTextNodes(node) {
  let textNodes = [];

  if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') {
    // 过滤空文本节点(避免处理换行、空格等无效节点)
    textNodes.push(node);
  }

  node.childNodes.forEach(childNode => {
    textNodes.push(...getTextNodes(childNode));
  });

  return textNodes;
}

关键修改点

  • 缩小搜索范围:将getTextNodes(document.body)改为getTextNodes(element),确保只在目标元素内查找文本节点,避免匹配页面无关内容。
  • 拆分文本节点:找到含匹配文本的节点后,拆分为「匹配前文本」「匹配内容」「匹配后文本」三部分,仅用<mark>包裹匹配部分。
  • 过滤无效节点:在getTextNodes中增加空文本判断,跳过换行、空格等无意义节点,减少无效处理。
  • 支持多匹配场景:原代码仅处理第一个匹配节点,现在遍历所有含匹配文本的节点,适配多处匹配的情况。

如果需要不区分大小写匹配,可修改匹配逻辑:

const nodeTextLower = nodeText.toLowerCase();
const textLower = text.toLowerCase();
const matchIndex = nodeTextLower.indexOf(textLower);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:05:31