当前位置:首页 > 行业动态 > 正文

htm转换js

将HTML转为JS可用模板字符串,用反引号包裹,嵌入${变量},如 ${content},或拼接字符串,动态生成 HTML结构

HTML 与 JavaScript 转换对照

HTML 元素/属性 JavaScript 实现方式
<div id="example"> const div = document.createElement('div'); div.id = 'example';
<p class="text">Hello</p> const p = document.createElement('p'); p.className = 'text'; p.textContent = 'Hello';
<button onclick="alert()"> const btn = document.createElement('button'); btn.addEventListener('click', () => alert(''));
<input type="text" /> const input = document.createElement('input'); input.type = 'text';
<img src="image.jpg"> const img = document.createElement('img'); img.src = 'image.jpg';

转换步骤详解

创建元素

  • HTML: <section></section>
  • JS:
    const section = document.createElement('section');

设置属性

  • HTML: <a href="#" target="_blank">
  • JS:
    const a = document.createElement('a');
    a.href = '#';
    a.target = '_blank';

添加文本内容

  • HTML: <h1>Title</h1>
  • JS:
    const h1 = document.createElement('h1');
    h1.textContent = 'Title'; // 或 h1.innerText = 'Title';

嵌套子元素

  • HTML:
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>
  • JS:
    const ul = document.createElement('ul');
    const li1 = document.createElement('li');
    li1.textContent = 'Item 1';
    const li2 = document.createElement('li');
    li2.textContent = 'Item 2';
    ul.appendChild(li1);
    ul.appendChild(li2);

插入到 DOM 中

  • HTML: <div></div>(直接写在页面中)
  • JS:
    document.body.appendChild(div); // 或指定父元素:container.appendChild(div);

事件绑定对比

HTML 事件 JavaScript 事件
<button onclick="func()"> btn.addEventListener('click', func);
<input onchange="handle()"> input.addEventListener('change', handle);
<a href="#" onmouseover="show()"> a.addEventListener('mouseover', show);

样式处理

HTML 样式 JavaScript 样式
<div style="color: red;"> div.style.color = 'red';
<p class="bold"> p.classList.add('bold');
<span data-role="highlight"> span.dataset.role = 'highlight';

常见问题与解答

问题 1:如何将 HTML 字符串直接转换为 DOM 元素?

解答:
使用 DOMParser 或创建一个临时容器:

htm转换js  第1张

// 方法 1: DOMParser
const htmlString = '<div><p>Hello</p></div>';
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
document.body.appendChild(doc.body.firstChild);
// 方法 2: 临时容器
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
document.body.appendChild(tempDiv.firstChild);

问题 2:如何批量转换 HTML 中的多个同类元素?

解答:
通过查询选择器获取所有目标元素,然后遍历转换:

// 示例:将所有 <a> 标签的 href 改为小写
const links = document.querySelectorAll('a');
links.forEach(link => {
  link.href = link.href.toLowerCase
0