<b> ↔ <strong>、<i> ↔ <em><font> → <span class>、<center> → <div style="text-align:center"><old-button> → <new-button>function swapTags(root, tagMap, options = {}) {
// tagMap: { 'old-tag': 'new-tag', 'b': 'strong' }
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_ELEMENT,
{
acceptNode: node => {
const newTag = tagMap[node.tagName.toLowerCase()];
return newTag ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
}
);
const toReplace = [];
while (walker.nextNode()) toReplace.push(walker.currentNode);
toReplace.forEach(oldEl => {
const newTag = tagMap[oldEl.tagName.toLowerCase()];
const newEl = document.createElement(newTag);
// 複製屬性(可選過濾)
[...oldEl.attributes].forEach(attr => {
if (!options.excludeAttrs?.includes(attr.name)) {
newEl.setAttribute(attr.name, attr.value);
}
});
// 移動子節點(保留事件監聽器、文字節點身分)
while (oldEl.firstChild) {
newEl.appendChild(oldEl.firstChild);
}
// 替換
oldEl.parentNode.replaceChild(newEl, oldEl);
// 回調
options.onReplace?.(oldEl, newEl);
});
}
// 使用範例
swapTags(document.querySelector('.content'), {
'b': 'strong',
'i': 'em',
'font': 'span', // 遷移 font 標籤
'center': 'div' // 遷移 center 標籤
}, {
excludeAttrs: ['style'], // 不複製內聯樣式,改用 CSS 類別
onReplace: (oldEl, newEl) => {
if (oldEl.tagName === 'FONT') {
// 轉換 font 屬性到 style/class
const size = oldEl.getAttribute('size');
if (size) newEl.style.fontSize = `${parseInt(size) * 3}px`; // 近似換算
}
}
});
function swapTagsHTML(container, tagMap) {
let html = container.innerHTML;
Object.entries(tagMap).forEach(([oldTag, newTag]) => {
const regexOpen = new RegExp(`<${oldTag}(\\s[^>]*)?>`, 'gi');
const regexClose = new RegExp(`</${oldTag}>`, 'gi');
html = html.replace(regexOpen, `<${newTag}$1>`).replace(regexClose, `${newTag}>`);
});
container.innerHTML = html;
// ⚠️ 所有子元素事件監聽器、輸入焦點、選區、表單狀態全失
}
import morphdom from 'morphdom';
function swapTagsMorphdom(container, tagMap) {
// 1. 產生目標 HTML
const targetHTML = container.innerHTML
.replace(/<(\/?)(\w+)([^>]*)>/g, (m, slash, tag, attrs) =>
tagMap[tag.toLowerCase()] ? `<${slash}${tagMap[tag.toLowerCase()]}${attrs}>` : m
);
// 2. 建立暫存容器
const temp = document.createElement('div');
temp.innerHTML = targetHTML;
// 3. Morphdom 智慧合併(保留未變更節點的狀態)
morphdom(container, temp, {
onBeforeElUpdated: (fromEl, toEl) => {
// 可選:同步特定屬性、保留特定類別
return true;
},
onNodeAdded: (node) => {
// 新增節點初始化(如綁定事件委派)
}
});
}
async function safeSwapAndRender(userHTML, container, tagMap) {
// 1. 淨化使用者輸入
const cleanHTML = DOMPurify.sanitize(userHTML, {
ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'strong', 'em', 'a', 'ul', 'ol', 'li', 'h1', 'h2', 'h3'],
ALLOWED_ATTR: ['href', 'target', 'rel', 'class']
});
// 2. 轉換標籤(在 DocumentFragment 操作,不觸發重排)
const doc = new DOMParser().parseFromString(cleanHTML, '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);
});
});
// 3. 替換容器內容
container.innerHTML = doc.body.innerHTML;
// 4. 事件委派(而非內聯 on*)
container.addEventListener('click', e => {
const link = e.target.closest('a[href]');
if (link) { /* 處理導航 */ }
});
}
<RichText content={html} tagMap={map} /> 內部用 dompurify + html-react-parserv-html="sanitizedHtml" + dompurify,或建立動態元件 <component :is="tag">{@html sanitizedHtml} + 客製化預處理器| 方法 | 耗時 (ms) | 記憶體 | 保留狀態 |
|---|---|---|---|
| DOM 遍歷 replaceChild | ~15-30 | 低 | ✅ 完整 |
| innerHTML 重設 | ~5-10 | 中 | ❌ 全失 |
| morphdom | ~20-40 | 中 | ✅ 大部分 |
| DocumentFragment 批次 | ~8-15 | 低 | ✅ 新節點 |
標籤切換首選 **DOM 遍歷 replaceChild**(安全保狀態),大規模結構變更用 **morphdom**,**永遠先淨化使用者輸入**,框架專案請遵循框架資料流而非直接操作 DOM。