简体   繁体   中英

Dynamically How to append more rows with columns into table using javascript

I want to append 3 rows into table with 3 column.I tried the following code,but it's not working.

html Code:

  <table width="50%" border="0" cellspacing="2" cellpadding="5" class="height">
    </table>    

javascriptcode:

  var table=document.getElementsByClassName('height') ;
  //creating inputfield with attribute
  var newField=document.createElement('input');
  newField.setAttribute('type','text');
  //creating <td> 
  var newTd=document.createElement('td');
  //appending newField into td
  newTd.appendChild(newField);
  //creating <tr> element
  var newTr=document.createElement('tr');
  //appending 3 <td>(newTd) elements,but here 3 <td>'s are not appending
  newTr.appendChild(newTd);
  newTr.appendChild(newTd);
  newTr.appendChild(newTd);
  //the above code was not working,if it works I want to append 3 <tr> into <table>.

I don't want to use external libraries(jquery,....) .

thanks

See http://coding.smashingmagazine.com/2013/10/06/inside-the-box-with-vanilla-javascript/ and goto to 'The API' section. This page explains about the default JS table DOM api. It consists of the following methods:

insertRow()
deleteRow()
insertCell()
deleteCell()
createCaption()
deleteCaption()
createTHead()
deleteTHead()

Does this solution suits your needs?

table.innerHTML = new Array(4).join(
    '<tr>' + new Array(4).join('<td><input type="text" /></td>') + '</tr>'
);

Here is a suggestion:

var table = document.getElementsByClassName('height')[0]; //I added [0] here

for (var i = 0; i < 3; i++) {
    var newField = document.createElement('input');
    newField.setAttribute('type', 'text');
    var newTd = document.createElement('td');
    newTd.appendChild(newField);
    var newTr = document.createElement('tr');
    newTr.appendChild(newTd);

    table.appendChild(newTr);  //you had forgoten this one
}

Demo here

Another try:

 var table = document.getElementsByTagName('table')[0]; // creates a template row with 3 cells var tr = document.createElement('tr'); tr.innerHTML = new Array(4).join( '<td><input type="text" /></td>' ); // appends 3 rows to the table by cloning the template row for (var i = 0; i < 3; i++) { table.appendChild(tr.cloneNode(true)); } 
 <table width="50%" border="0" cellspacing="2" cellpadding="5" class="height"></table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM