2026-10-24 18:34:57
使用 JavaScript 编译 HTML 的核心是通过 DOM(文档对象模型) 解析、修改和生成 HTML 结构。以下是具体步骤和示例:
1. 创建 DOM 对象使用 DOMParser 将 HTML 字符串解析为 DOM 对象,以便后续操作:
const htmlString = '<div id="container"><p class="text">Hello</p></div>';const parser = new DOMParser();const doc = parser.parseFromString(htmlString, "text/html");2. 操作 DOM 元素通过 DOM 方法获取、修改或创建元素:
获取元素:
// 根据 ID 获取const container = doc.getElementById('container');// 根据类名获取(返回集合)const texts = doc.getElementsByClassName('text');// 根据标签名获取(返回集合)const paragraphs = doc.getElementsByTagName('p');修改元素属性:
const pElement = doc.querySelector('p'); // 使用 CSS 选择器获取pElement.setAttribute('class', 'new-class'); // 设置属性const attrValue = pElement.getAttribute('class'); // 获取属性pElement.removeAttribute('class'); // 移除属性修改元素内容:
// 设置 HTML 内容(包含标签)pElement.innerHTML = '<strong>New Content</strong>';// 设置纯文本内容pElement.innerText = 'Plain Text';// 添加子元素const newSpan = doc.createElement('span');newSpan.innerText = ' Added Span';pElement.appendChild(newSpan);创建新元素:
const newDiv = doc.createElement('div');newDiv.id = 'new-div';newDiv.innerHTML = '<p>Created Dynamically</p>';// 插入到指定位置const parent = doc.getElementById('container');parent.insertBefore(newDiv, parent.firstChild); // 插入到开头将修改后的 DOM 对象转换回 HTML 字符串:
const compiledHtml = doc.documentElement.outerHTML;console.log(compiledHtml);// 输出示例:// <html><head></head><body><div id="container"><p class="new-class"><strong>New Content</strong><span> Added Span</span></p><div id="new-div"><p>Created Dynamically</p></div></div></body></html>完整示例// 1. 解析 HTML 字符串const htmlString = '<div id="container"><p class="text">Hello</p></div>';const parser = new DOMParser();const doc = parser.parseFromString(htmlString, "text/html");// 2. 操作 DOMconst pElement = doc.querySelector('p');pElement.innerHTML = '<strong>Modified</strong>';const newDiv = doc.createElement('div');newDiv.id = 'dynamic-div';newDiv.innerText = 'New Element';const container = doc.getElementById('container');container.appendChild(newDiv);// 3. 输出结果const result = doc.documentElement.outerHTML;console.log(result);关键点总结此方法适用于动态生成、修改或分析 HTML 结构,常见于前端框架(如 React/Vue 的虚拟 DOM 实现)或服务器端 HTML 生成场景。