萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

JavaScript 動態替換 HTML 標籤技巧:DOM 操作、innerHTML 與安全替換策略

動態替換標籤的常見需求

富文本編輯器標籤轉換(<b>→<strong>)、Markdown 渲染後調整、舊內容遷移、元件庫升級。核心挑戰在於**保留內容與事件綁定**、**防止 XSS**、**維持效能**。

方案一:DOM 遍歷替換(最安全、保留事件/引用)

function replaceTag(rootElement, targetTag, newTag, options = {}) {
  // 建立 TreeWalker 只遍歷元素節點
  const walker = document.createTreeWalker(
    rootElement,
    NodeFilter.SHOW_ELEMENT,
    { acceptNode: node => node.tagName.toLowerCase() === targetTag.toLowerCase() 
      ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP }
  );

  const nodesToReplace = [];
  while (walker.nextNode()) nodesToReplace.push(walker.currentNode);

  nodesToReplace.forEach(oldEl => {
    const newEl = document.createElement(newTag);
    
    // 1. 複製屬性(可選:過濾/轉換屬性)
    [...oldEl.attributes].forEach(attr => {
      if (!options.excludeAttrs?.includes(attr.name)) {
        newEl.setAttribute(attr.name, attr.value);
      }
    });
    
    // 2. 移動子節點(保留事件監聽器、文字節點引用)
    while (oldEl.firstChild) {
      newEl.appendChild(oldEl.firstChild);
    }
    
    // 3. 替換
    oldEl.parentNode.replaceChild(newEl, oldEl);
  });
}

// 使用範例:將所有 b 標籤改為 strong
replaceTag(document.querySelector('.content'), 'b', 'strong');

方案二:innerHTML 字串替換(簡單但有風險)

function replaceTagHTML(container, targetTag, newTag) {
  // ⚠️ 風險:破壞事件監聽器、輸入焦點、選區、表單狀態
  // ⚠️ XSS 風險:若容器包含使用者輸入未編碼內容
  container.innerHTML = container.innerHTML
    .replace(new RegExp(`<${targetTag}(\\s[^>]*)?>`, 'gi'), `<${newTag}$1>`)
    .replace(new RegExp(`</${targetTag}>`, 'gi'), ``);
}

僅適用於:靜態內容、無事件綁定、無使用者輸入、一次性渲染**

方案三:虛擬 DOM Diff(大量更新、效能敏感)

使用 morphdom、morphdom 或框架內建 diff(React/Vue/Svelte):

import morphdom from 'morphdom';

function replaceTagsWithMorphdom(container, tagMap) {
  // 建立目標 HTML 字串
  const targetHTML = container.innerHTML
    .replace(/<(\/?)(\w+)([^>]*)>/g, (match, slash, tag, attrs) => {
      const newTag = tagMap[tag.toLowerCase()];
      return newTag ? `<${slash}${newTag}${attrs}>` : match;
    });
  
  // 建立臨時容器做 morph
  const temp = document.createElement('div');
  temp.innerHTML = targetHTML;
  morphdom(container, temp, {
    onBeforeElUpdated: (fromEl, toEl) => {
      // 可選:保留特定屬性/事件
      return true; // 繼續 diff
    }
  });
}

安全替換策略:輸入端淨化 + 輸出端編碼

// 完整流程範例
async function safeReplaceAndRender(userHTML, container) {
  // 1. 淨化(移除危險標籤/屬性)
  const cleanHTML = DOMPurify.sanitize(userHTML, {
    ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'strong', 'em', 'a', 'ul', 'ol', 'li'],
    ALLOWED_ATTR: ['href', 'target', 'rel']
  });
  
  // 2. 標籤轉換(如 b→strong)
  const converted = convertTags(cleanHTML, { b: 'strong', i: 'em' });
  
  // 3. 渲染(使用 textContent + 選擇性 innerHTML)
  container.innerHTML = converted; // 已淨化,相對安全
  
  // 4. 附加事件委派(而非內聯 on* 屬性)
  container.addEventListener('click', e => {
    if (e.target.matches('a[href]')) { /* 處理連結 */ }
  });
}

function convertTags(html, tagMap) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  Object.entries(tagMap).forEach(([oldTag, newTag]) => {
    doc.querySelectorAll(oldTag).forEach(el => {
      const newEl = document.createElement(newTag);
      [...el.attributes].forEach(a => newEl.setAttribute(a.name, a.value));
      el.replaceWith(newEl);
      // 移動子節點在 replaceWith 後自動處理
    });
  });
  return doc.body.innerHTML;
}

效能優化建議

  • 大量節點時使用 DocumentFragment 批次操作
  • 避免在迴圈中觸發重排(讀寫分離)
  • 考慮 requestIdleCallback 分批處理
  • 虛擬滾動容器外的節點勿處理

動態替換標籤以 **DOM 遍歷替換** 為首選(安全、保狀態),大規模更新改用 **morphdom** 類函式庫,**永遠先淨化使用者輸入**,再進行轉換與渲染。

copyright © 萬盛學電腦網 all rights reserved