- Javascript Add Table Row
- 2 Answers 2
- Table insertRow() Method
- Browser Support
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- HTMLTableElement: insertRow() method
- Syntax
- Parameters
- Return value
- Exceptions
- Examples
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Add/Delete table rows dynamically using JavaScript
- Easy Javascript Add more Rows with delete functionality
Javascript Add Table Row
Currently that produces new rows within a row. I don’t want that. I only want a new row not in a row. When I click the + I want it to produce:
I suggest you take time to look at KnockoutJS or AngularJS so that you don’t have to fiddle with HTML manually. The frameworks will do the dirty job for you.
2 Answers 2
Don’t use innerHTML to modify tables, it will throw an error in most versions of IE. Use DOM methods.
Don’t use an A element when you don’t want an link or anchor, use an element like a button or styled span.
You can’t add a TR element as a child of a DIV element, it’s invalid. You must add it as a child of a table section element (thead, tbody or tfoot). In some cases you can add rows to a table element but some browsers don’t like that either.
So to create the new row, use:
var tr = document.createElement('tr'); var td = tr.appendChild(document.createElement('td')); // Much better to add a class and do this stuff with CSS td.style.valign = 'middle'; var span = document.createElement('span'); span.style.fontWeight = 'bold'; span.appendChild(docment.createTextNode('URL ' + i); td = tr.appendChild(document.createElement('td')); var input = td.appendChild(document.createElement('input')); input.name = 'url' + i; input.type = 'text'; input.size = '40'
now append the TR to a table section somewhere.
document.getElementById('myTable').tBodies[0].appendChild(tr);
The whole thing looks like:
var i = 1; function changeIt()
You could build the row to add in the bottom table and have it hidden, then just clone it and modify the bits that need it.
Table insertRow() Method
The insertRow() method inserts the new row(s) at the specified index in the table.
Tip: Use the deleteRow() method to remove a row.
Browser Support
Syntax
Parameter Values
Value | Description |
---|---|
index | Required in Firefox and Opera, optional in IE, Chrome and Safari. A number that specifies the position of the row to insert (starts at 0). The value of 0 results in that the new row will be inserted at the first position. |
The value of -1 can also be used, this results in a new row being inserted at the last position.
This parameter is required in Firefox and Opera, but optional in Internet Explorer, Chrome and Safari.
Technical Details
More Examples
Example
function myCreateFunction() <
var table = document.getElementById(«myTable»);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = «NEW CELL1»;
cell2.innerHTML = «NEW CELL2»;
>
function myDeleteFunction() document.getElementById(«myTable»).deleteRow(0);
>
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
HTMLTableElement: insertRow() method
The HTMLTableElement.insertRow() method inserts a new row ( ) in a given , and returns a reference to the new row.
let specific_tbody = document.getElementById(tbody_id); let row = specific_tbody.insertRow(index);
Syntax
Parameters
The row index of the new row. If index is -1 or equal to the number of rows, the row is appended as the last row. If index is omitted it defaults to -1 .
Return value
An HTMLTableRowElement that references the new row.
Exceptions
Thrown if index is greater than the number of rows.
Examples
This example uses insertRow(-1) to append a new row to a table.
HTML
table id="my-table"> tr> td>Row 1td> tr> tr> td>Row 2td> tr> tr> td>Row 3td> tr> table>
JavaScript
function addRow(tableID) // Get a reference to the table let tableRef = document.getElementById(tableID); // Insert a row at the end of the table let newRow = tableRef.insertRow(-1); // Insert a cell in the row at index 0 let newCell = newRow.insertCell(0); // Append a text node to the cell let newText = document.createTextNode("New bottom row"); newCell.appendChild(newText); > // Call addRow() with the table's ID addRow("my-table");
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Add/Delete table rows dynamically using JavaScript
You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell).
function deleteRow(row) < var i=row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); >function insRow() < var x=document.getElementById('POITable'); // deep clone the targeted row var new_row = x.rows[1].cloneNode(true); // get the total number of rows var len = x.rows.length; // set the innerHTML of the first row new_row.cells[0].innerHTML = len; // grab the input from the first cell and update its ID and value var inp1 = new_row.cells[1].getElementsByTagName('input')[0]; inp1.id += len; inp1.value = ''; // grab the input from the first cell and update its ID and value var inp2 = new_row.cells[2].getElementsByTagName('input')[0]; inp2.id += len; inp2.value = ''; // append the new row to the table x.appendChild( new_row ); >
function deleteRow(row) < var i = row.parentNode.parentNode.rowIndex; document.getElementById('POITable').deleteRow(i); >function insRow()
POI Latitude Longitude Delete? Add Rows? 1
@Pow: You’re welcome. I put together another example. This one places your header row in a element, and the rest in a element. Additionally, I updated to code to update the row numbers and IDs when deleting a row, and moved some of the code into its own function.
I have one more concern. What if I don’t have any created row? Suppose I want to do the exact same thing. But the 2nd row (that is being cloned) does not exist initially.
@Pow: Using the example in my comment above, change the line that makes an initial clone from the first row to this: clone = tbody.removeChild(tbody.rows[0]); . So you’d send that row from the server, and remove it right away, storing it in clone . Then create another button that will add that initial row. It could be that you’d just want a single button outside the table for adding rows anyway since there’s not much reason to have the same button repeating over and over in the table.
Easy Javascript Add more Rows with delete functionality
Enter Title
This seems a lot cleaner than the answer above.
var maxID = 0; function getTemplateRow() < var x = document.getElementById("templateRow").cloneNode(true); x.id = ""; x.style.display = ""; x.innerHTML = x.innerHTML.replace(//, ++maxID); return x; > function addRow() id name
@BradLaney Why learning jQuery for something like this? I don’t have nothing against jQuery but, so much people relies on jQuery for so simple things which can be done using pure JS. For few years people will forgot about, even, basics of JS.
If you put a delete button on each row, then:
And the deleteRow function can be:
function deleteRow(el) < // while there are parents, keep going until reach TR while (el.parentNode && el.tagName.toLowerCase() != 'tr') < el = el.parentNode; >// If el has a parentNode it must be a TR, so delete it // Don't delte if only 3 rows left in table if (el.parentNode && el.parentNode.rows.length > 3) < el.parentNode.removeChild(el); >>
If all your rows have the same content, it will be much faster to add a row by cloning an existing row:
function addRow(tableID) < var table = document.getElementById(tableID); if (!table) return; var newRow = table.rows[1].cloneNode(true); // Now get the inputs and modify their names var inputs = newRow.getElementsByTagName('input'); for (var i=0, iLen=inputs.length; i// Add the new row to the tBody (required for IE) var tBody = table.tBodies[0]; tBody.insertBefore(newRow, tBody.lastChild); >
You can add a row to a table in the most easiest way like this :-
I found this as an easiest way to add row . The awesome thing about this is that it doesn’t change the already present table contents even if it contains input elements .
row = ` ` $("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
1 & 2: innerHTML can take HTML as well as text. You could do something like:
May or may not be the best way to do it, but you could do it that way.
3: I would just use a global variable that holds the number of POIs and increment/decrement it each time.
Here Is full code with HTML,CSS and JS.
body < background-color: #efefef; color: #3a3a3a; >a, a:visited < color: #1e73be; >a:hover, a:focus, a:active < color: #000000; >body .grid-container < max-width: 1200px; >body, button, input, select, textarea < font-family: "Open Sans", sans-serif; >.entry-content>[class*="wp-block-"]:not(:last-child) < margin-bottom: 1.5em; >.main-navigation .main-nav ul ul li a < font-size: 14px; >@media (max-width:768px) < .main-title < font-size: 30px; >h1 < font-size: 30px; >h2 < font-size: 25px; >> .top-bar < background-color: #636363; color: #ffffff; >.top-bar a, .top-bar a:visited < color: #ffffff; >.top-bar a:hover < color: #303030; >.site-header < background-color: #ffffff; color: #3a3a3a; >.site-header a, .site-header a:visited < color: #3a3a3a; >.main-title a, .main-title a:hover, .main-title a:visited < color: #222222; >.site-description < color: #757575; >.main-navigation, .main-navigation ul ul < background-color: #222222; >.main-navigation .main-nav ul li a, .menu-toggle < color: #ffffff; >.main-navigation .main-nav ul li:hover>a, .main-navigation .main-nav ul li:focus>a, .main-navigation .main-nav ul li.sfHover>a < color: #ffffff; background-color: #3f3f3f; >button.menu-toggle:hover, button.menu-toggle:focus, .main-navigation .mobile-bar-items a, .main-navigation .mobile-bar-items a:hover, .main-navigation .mobile-bar-items a:focus < color: #ffffff; >.main-navigation .main-nav ul li[class*="current-menu-"]>a < color: #ffffff; background-color: #3f3f3f; >.main-navigation .main-nav ul li[class*="current-menu-"]>a:hover, .main-navigation .main-nav ul li[class*="current-menu-"] .sfHover>a < color: #ffffff; background-color: #3f3f3f; >.navigation-search input[type="search"], .navigation-search input[type="search"]:active < color: #3f3f3f; background-color: #3f3f3f; >.navigation-search input[type="search"]:focus < color: #ffffff; background-color: #3f3f3f; >.main-navigation ul ul < background-color: #3f3f3f; >.main-navigation .main-nav ul ul li a < color: #ffffff; >.main-navigation .main-nav ul ul li:hover>a, .main-navigation .main-nav ul ul li:focus>a, .main-navigation .main-nav ul ul li.sfHover>a < color: #ffffff; background-color: #4f4f4f; >.main-navigation . main-nav ul ul li[class*="current-menu-"]>a < color: #ffffff; background-color: #4f4f4f; >.main-navigation .main-nav ul ul li[class*="current-menu-"]>a:hover, .main-navigation .main-nav ul ul li[class*="current-menu-"] .sfHover>a < color: #ffffff; background-color: #4f4f4f; >.separate-containers .inside-article, .separate-containers .comments-area, .separate-containers .page-header, .one-container .container, .separate-containers .paging-navigation, .inside-page-header < background-color: #ffffff; >.entry-meta < color: #595959; >.entry-meta a, .entry-meta a:visited < color: #595959; >.entry-meta a:hover < color: #1e73be; >.sidebar .widget < background-color: #ffffff; >.sidebar .widget .widget-title < color: #000000; >.footer-widgets < background-color: #ffffff; >.footer-widgets .widget-title < color: #000000; >.site-info < color: #ffffff; background-color: #222222; >.site-info a, .site-info a:visited < color: #ffffff; >.site-info a:hover < color: #606060; >.footer-bar .widget_nav_menu .current-menu-item a < color: #606060; >input[type="text"], input[type="email"], input[type="url"], input[type="password"], input[type="search"], input[type="tel"], input[type="number"], textarea, select < color: #666666; background-color: #fafafa; border-color: #cccccc; >input[type="text"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="password"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="number"]:focus, textarea:focus, select:focus < color: #666666; background-color: #ffffff; border-color: #bfbfbf; >button, html input[type="button"], input[type="reset"], input[type="submit"], a.button, a.button:visited, a.wp-block-button__link:not(.has-background) < color: #ffffff; background-color: #666666; >button:hover, html input[type="button"]:hover, input[type="reset"]:hover, input[type="submit"]:hover, a.button:hover, button:focus, html input[type="button"]:focus, input[type="reset"]:focus, input[type="submit"]:focus, a.button:focus, a.wp-block-button__link:not(.has-background):active, a.wp-block-button__link:not(.has-background):focus, a.wp-block-button__link:not(.has-background):hover < color: #ffffff; background-color: #3f3f3f; >.generate-back-to-top, .generate-back-to-top:visited < background-color: rgba( 0, 0, 0, 0.4); color: #ffffff; >.generate-back-to-top:hover, .generate-back-to-top:focus < background-color: rgba( 0, 0, 0, 0.6); color: #ffffff; >.entry-content .alignwide, body:not(.no-sidebar) .entry-content .alignfull < margin-left: -40px; width: calc(100% + 80px); max-width: calc(100% + 80px); >@media (max-width:768px) < .separate-containers .inside-article, .separate-containers .comments-area, .separate-containers .page-header, .separate-containers .paging-navigation, .one-container .site-content, .inside-page-header < padding: 30px; >.entry-content .alignwide, body:not(.no-sidebar) .entry-content .alignfull < margin-left: -30px; width: calc(100% + 60px); max-width: calc(100% + 60px); >> .rtl .menu-item-has-children .dropdown-menu-toggle < padding-left: 20px; >.rtl .main-navigation .main-nav ul li.menu-item-has-children>a < padding-right: 20px; >.one-container .sidebar .widget < padding: 0px; >.append_row < color: black !important; background-color: #FFD6D6 !important; border: 1px #ccc solid !important; >.append_column < color: black !important; background-color: #D6FFD6 !important; border: 1px #ccc solid !important; >table#my-table td < width: 50px; height: 27px; border: 1px solid #D3D3D3; text-align: center; padding: 0; >div#my-container input < padding: 5px; font-size: 12px !important; width: 100px; margin: 2px; >.row < background-color: #FFD6D6 !important; >.col
Small