如何用js写html

要用JavaScript编写HTML,首先需要创建一个HTML文档结构,然后使用JavaScript操作DOM元素,以下是一个简单的示例,包括一个小标题和一个单元表格:

1、创建一个HTML文档结构:




    
    
    用JavaScript写HTML示例


    

2、在script.js文件中编写JavaScript代码:

// 获取容器元素
const container = document.getElementById('container');
// 创建小标题
const h1 = document.createElement('h1');
h1.textContent = '这是一个小标题';
container.appendChild(h1);
// 创建表格
const table = document.createElement('table');
table.border = '1';
// 创建表头
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
const headerCell1 = document.createElement('th');
headerCell1.textContent = '列1';
const headerCell2 = document.createElement('th');
headerCell2.textContent = '列2';
headerRow.appendChild(headerCell1);
headerRow.appendChild(headerCell2);
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表格内容
const tbody = document.createElement('tbody');
for (let i = 0; i < 5; i++) {
    const row = document.createElement('tr');
    const cell1 = document.createElement('td');
    cell1.textContent = 数据${i + 1}1;
    const cell2 = document.createElement('td');
    cell2.textContent = 数据${i + 1}2;
    row.appendChild(cell1);
    row.appendChild(cell2);
    tbody.appendChild(row);
}
table.appendChild(tbody);
// 将表格添加到容器中
container.appendChild(table);

这个示例中,我们首先创建了一个HTML文档结构,然后在script.js文件中编写了JavaScript代码,我们使用document.createElement方法创建了小标题、表格、表头和表格内容,并将它们添加到了容器元素中。

分享文章:如何用js写html
本文路径:http://www.csdahua.cn/qtweb/news36/376586.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网