Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  1] [ 3]  / answers: 1 / hits: 11313  / 6 Years ago, sat, june 16, 2018, 12:00:00

I'd like to write <td> tags with JavaSctipt in my HTML code.
I'm building a <table> in the main code and I'd like to continue it with a <script>, adding rows in the division.



<body>
<table>
<tr>
<td>First</td>
</tr>
<div id=searchOutput></div>
<tr>
<td>Last</td>
</tr>
</table>
<script>
document.getElementById(searchOutput).innerHTML = <tr><td>Middle<td><tr>;
</script>
</body>




The problem is that the <script> creates another table in a strange way.



Chrome
Chrome



Is there a way to add rows without writing all code (including <table> tags) in the <script>?


More From » html

 Answers
10

For insert new row in the table, you can use Table insertRow() and insertCell() Methods. The insertRow() methods creates an empty <tr> element and adds it to a table. The insertCell() method inserts a cell into the current row.



See the code below:





function addRows() {
var table = document.getElementById( 'myTable' ),
row = table.insertRow(0),
cell1 = row.insertCell(0),
cell2 = row.insertCell(1);

cell1.innerHTML = 'Cell 1';
cell2.innerHTML = 'Cell 2';
}

table {
border: 1px solid #999;
border-collapse: collapse;
width: 100%
}
td {
border: 1px solid #999
}

<p>
<button onclick=addRows()>Add a new row</button>
</p>
<table id=myTable></table>




[#12929] Thursday, June 14, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brendan

Total Points: 426
Total Questions: 110
Total Answers: 94

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;