Home Web Front-end JS Tutorial How to dynamically create a table with JavaScript_javascript skills

How to dynamically create a table with JavaScript_javascript skills

May 16, 2016 pm 03:31 PM

Two ways to dynamically create tables using JavaScript are shared with you. The specific implementation is as follows

Method 1: The most original method, create elements one by one

var a1=document.createElement("table");

var a2=document.createElement("tbody");

var a3=document.createElement("tr");

var a4=document.createElement("td");

//开始appendchild()追加各个元素

a3.appendChild(a4);

a2.appendChild(a3);

a1.appendChild(a2); 
Copy after login

Method 2: Use the functions contained in the table object: insert rows and insert columns

var tabNode=document.createElement("table");

var trNode=tabNode.insertRow();

var tdNode=trNode.insertCell;

tabNode.innerHTML="这是采用table对象里面的函数创建的"
注意:利用原始方法,一个个createElement时候,必须要添加一个tbody对象
//获取<table>标签的兄弟节点

// var node3=tabnode.previousSibling;//前一个节点 获取对此对象的上一个兄弟对象的引用。

// alert("previous--node3:"+node3);//#text

// 如果<table>后面有回车符,高版本的IE和火狐会识别成 “空白文本”#text,

// 而低版本IE会直接越过-----不光是<table>节点,其它节点也一样

// 表格的,<table>标签和<tr>标签中间,其实还隐藏着一个<tbody>标签----表格体

Copy after login

Dynamic creation and deletion:
Create a table by entering values:

function createTable(){ 
    tableNode=document.createElement("table");//获得对象 
   tableNode.setAttribute("id","table") 
   var row=parseInt(document.getElementsByName("row1")[0].value);//获得行号 
   //alert(row); 
   if(row<=0 || isNaN(row) ){ 
    alert("输入的行号错误,不能创建表格,请重新输入:"); 
    return; 
   } 
   var cols=parseInt(document.getElementsByName("cols1")[0].value); 
   if(isNaN(cols) || cols<=0){ 
    alert("输入的列号错误,不能创建表格,请重新输入:"); 
    return; 
   } 
   //上面确定了 现在开始创建 
   for(var x=0;x<row;x++){ 
    var trNode=tableNode.insertRow(); 
    for(var y=0;y<cols;y++){ 
     var tdNode=trNode.insertCell(); 
     tdNode.innerHTML="单元格"+(x+1)+"-"+(y+1); 
    } 
   } 
   document.getElementById("div1").appendChild(tableNode);//添加到那个位置 
  } 
Copy after login

Delete row:

function delRow(){ 
  //要删除行,必须得到table对象才能删除,所以在创建的时候必须要设置table对象的 id 方便操作 
  var tab=document.getElementById("table");//获得table对象 
  if(tab==null){ 
   alert("删除的表不存在!") 
   return; 
  } 
  var rows=parseInt(document.getElementsByName("delrow1")[0].value);//获得要删除的对象 
  if(isNaN(rows)){ 
   alert("输入的行不正确。请输入要删除的行。。。"); 
   return; 
  } 
  if (rows >= 1 && rows <= tab.rows.length) { 
   tab.deleteRow(rows-1); 
   }else{ 
    alert("删除的行不存在!!"); 
    return ; 
   } 
   
 } 
Copy after login

Delete column:

//删除列要麻烦些, 要通过行来进行删除 
  // 一行的cells的长度就是列的个数 
  //tab.rows[x].deleteCell(cols-1) 
  function delCols(){ 
   //获得table对象 
   var tab=document.getElementById("table"); 
    
   if(tab==null){ 
    alert("删除的表不存在!!"); 
    return ; 
   } 
   //获得文本框里面的内容 
   var cols=parseInt(document.getElementsByName("delcols1")[0].value); 
   //检查是否可靠 
   if(isNaN(cols)){ 
    alert("输入不正确。请输入要输出的列。。"); 
    return; 
   } 
   if(!(cols>=1 && cols<tab.rows[0].cells.length)){ 
    alert("您要删除的行不存在!!"); 
    return; 
   } 
   for(var x=0;x<tab.rows.length;x++){//所有的行 
    tab.rows[x].deleteCell(cols-1); 
   } 
  } 
Copy after login

Full code:

<!DOCTYPE html> 
<html> 
 <head> 
 <title>createTable2.html</title> 
 <style type="text/css"> 
  table{ 
   border:#00ffff solid 2px; 
   border-collapse:collapse; 
  } 
  td{ 
   border:#8080ff solid 2px; 
    padding:10px; 
  } 
 </style> 
 <script type="text/javascript"> 
  var tableNode; 
  function createTable(){ 
    tableNode=document.createElement("table");//获得对象 
   tableNode.setAttribute("id","table") 
   var row=parseInt(document.getElementsByName("row1")[0].value);//获得行号 
   //alert(row); 
   if(row<=0 || isNaN(row) ){ 
    alert("输入的行号错误,不能创建表格,请重新输入:"); 
    return; 
   } 
   var cols=parseInt(document.getElementsByName("cols1")[0].value); 
   if(isNaN(cols) || cols<=0){ 
    alert("输入的列号错误,不能创建表格,请重新输入:"); 
    return; 
   } 
   //上面确定了 现在开始创建 
   for(var x=0;x<row;x++){ 
    var trNode=tableNode.insertRow(); 
    for(var y=0;y<cols;y++){ 
     var tdNode=trNode.insertCell(); 
     tdNode.innerHTML="单元格"+(x+1)+"-"+(y+1); 
    } 
   } 
   document.getElementById("div1").appendChild(tableNode);//添加到那个位置 
  } 
  function delRow(){ 
   //要删除行,必须得到table对象才能删除,所以在创建的时候必须要设置table对象的 id 方便操作 
   var tab=document.getElementById("table");//获得table对象 
   if(tab==null){ 
    alert("删除的表不存在!") 
    return; 
   } 
   var rows=parseInt(document.getElementsByName("delrow1")[0].value);//获得要删除的对象 
   if(isNaN(rows)){ 
    alert("输入的行不正确。请输入要删除的行。。。"); 
    return; 
   } 
   if (rows >= 1 && rows <= tab.rows.length) { 
    tab.deleteRow(rows-1); 
    }else{ 
     alert("删除的行不存在!!"); 
     return ; 
    } 
    
  } 
  //删除列要麻烦些, 要通过行来进行删除 
  // 一行的cells的长度就是列的个数 
  //tab.rows[x].deleteCell(cols-1) 
  function delCols(){ 
   //获得table对象 
   var tab=document.getElementById("table"); 
    
   if(tab==null){ 
    alert("删除的表不存在!!"); 
    return ; 
   } 
   //获得文本框里面的内容 
   var cols=parseInt(document.getElementsByName("delcols1")[0].value); 
   //检查是否可靠 
   if(isNaN(cols)){ 
    alert("输入不正确。请输入要输出的列。。"); 
    return; 
   } 
   if(!(cols>=1 && cols<tab.rows[0].cells.length)){ 
    alert("您要删除的行不存在!!"); 
    return; 
   } 
   for(var x=0;x<tab.rows.length;x++){//所有的行 
    tab.rows[x].deleteCell(cols-1); 
   } 
  } 
  
 </script> 
 </head> 
 
 <body> 
 行:<input type="text" name="row1"/> 
 列:<input type="text" name="cols1"/> 
 <input type="button" value="创建表格" onclick="createTable()"/><br/> 
  
 <input type="text" name="delrow1"/> 
 <input type="button" value="删除行" onclick="delRow()"/><br/> 
  
 <input type="text" name="delcols1"/> 
 <input type="button" value="删除列" onclick="delCols()"/><br> 
 <div id="div1"></div> 
 </body> 
</html> 
Copy after login

Effect demonstration:

The above are two ways to dynamically create tables using JavaScript. I hope you like them.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

10 Ways to Instantly Increase Your jQuery Performance 10 Ways to Instantly Increase Your jQuery Performance Mar 11, 2025 am 12:15 AM

This article outlines ten simple steps to significantly boost your script's performance. These techniques are straightforward and applicable to all skill levels. Stay Updated: Utilize a package manager like NPM with a bundler such as Vite to ensure

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Using Passport With Sequelize and MySQL Using Passport With Sequelize and MySQL Mar 11, 2025 am 11:04 AM

Sequelize is a promise-based Node.js ORM. It can be used with PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. In this tutorial, we will be implementing authentication for users of a web app. And we will use Passport, the popular authentication middlew

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

See all articles