how to use getElementById to get the table specified with id - javascript

i want to use js to add one row in an exsiting table,however i got an error:document.getElementById() is null,here is my code:
<!DOCTYPE html>
<html>
<head>
<title>use js to create one row</title>
</head>
<body >
<tr id="table">
<td>row 1</td>
</tr>
<script>
window.onload = function(){
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.getElementById("table");
tr.appendChild(rows);
}
</script>
</body>
</html>

Because tr is invalid outside of a table, the browser is basically ignoring the tr element entirely and just putting the text row 1 directly in body, which is why getElementById didn't return an element; it was never created by the browser when parsing the HTML.
Put the tr in a table (and ideally in a tbody):
<table>
<tbody id="tbody">
<tr>
<td>row 1</td>
</tr>
</tbody>
</table>
and append to the tbody, being sure to create a row (tr) as well as a td since your apparent goal is to add a row:
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.createElement("tr");
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
It's also almost never useful to use the load event on window. Instead, just put your script at the very end of the HTML, just before the closing </body> tag.
Live example:
<table>
<tbody id="tbody">
<tr>
<td>row 1</td>
</tr>
</tbody>
</table>
<script>
(function() {
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.createElement("tr");
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
})();
</script>

Related

How to add table row and colums at specific index

How to add a table row or table column at specific index by on clicking the table cells, same as excel sheet.
<table >
<tr>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Add Row Script:
function AppendRows() {
var tableRows = document.getElementById('myTable'),
row = tableRows.insertRow(tableRows.rows.length);
row.height = '50';
for (var i = 0; i < tableRows.rows[0].cells.length; i++) {
row.insertCell(i), i, 'row';
}
}
Here is an example on how you can insert a new row. There are several approaches you can go with but basically this is the way
function insertrow() {
var newRowIndex = 1;
var row1 = document.getElementById("table").childNodes[1].childNodes[newRowIndex];
var newRow = document.createElement("tr");
var col0 = document.createElement("td");
col0.innerHTML = "newA";
newRow.appendChild(col0);
var col1 = document.createElement("td");
col1.innerHTML = "newB";
newRow.appendChild(col1);
var col2 = document.createElement("td");
col2.innerHTML = "newC";
newRow.appendChild(col2);
row1.parentNode.insertBefore(newRow, row1);
}
<button onclick="insertrow()">Insert row</button>
<table id="table">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
</table>
Also i'd suggest you take a look at the insertBefore documentation.
Here's a method to insert a row after a row is clicked. The new row is added immediately after the clicked row, so new rows can be added at different locations.
Let's walk through it:
First we setup an event listener on the table to listen for clicks on the row elements. When a row is clicked, we call the the appendRow method to add a new row, and pass the index where we want the row to appear.
We're using delegation here so dynamically added rows will be included in the event listener.
The appendRow method adds a new row at the defined index, then adds a few table cells for presentation purposes.
var tableEl = document.getElementById('table');
tableEl.addEventListener('click', function(event) {
var el = event.target;
if (el.closest('tr') && el.closest('tbody')) {
var trow = el.parentElement;
var tbody = trow.parentElement;
var index = Array.prototype.indexOf.call(tbody.children, trow);
appendRow(tbody, index + 1);
}
});
function appendRow(tbody, index) {
var row = tbody.insertRow(index);
var cells = ['A', 'B', 'C'];
cells.forEach(function(cell, idx) {
var newCell = row.insertCell(idx);
var newText = document.createTextNode(`Row ${index} - ${cell}`);
newCell.appendChild(newText);
});
}
table {
table-layout: fixed;
width: 100%;
}
td {
border: 1px solid gray;
}
<table id="table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</tbody>
</table>

move first Tr to thead and replace td to th using jquery

I have a string returned from an ajax call like this
<table>
<tbody>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>
Now I want to restructure this to
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr></thead>
<tbody>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>
How can I do this in jQuery?
The line below inserts a thead and copies the first tr into it
$(data.d).prepend("<thead></thead>").find("thead").html($(data.d).find("tr:eq(0)"))
I am trying to remove the first row in tbody after the previous line by using this line
$(data.d).find("tbody tr:eq(0)").remove()
How can I append thead,move first tr in tbody to it, replace all td inside that to th and finally remove the first tr from tbody
Some step by step solution,
var jsonString = "<table><tbody><tr><td>Name</td><td>Age</td></tr><tr><td>Ron</td><td>28</td></tr></tbody></table>";
var t =$(jsonString); //jquery Table Object
var firstTR = $('tr:first',t); //geting firstTR
$('<thead></thead>')
.prependTo(t)
.append(
$('td',firstTR).map(
function(i,e){
return $("<th>").html(e.textContent).get(0);
}
)
);
firstTR.remove();//removing First TR
$("#div").html(t);
//Output
console.log(t.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">
</div>
My proposal is:
get the first row and for each cell create the corresponding th cell
prepend to table body the table header, append the header cells created
remove the first table body row
$(function () {
var th = $('table tbody tr:first td').map(function(i, e) {
return $('<th>').append(e.textContent).get(0);
});
$('table tbody').prepend($('<thead>').append(th)).find('tr:first').remove();
console.log($('table').html());
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table>
<tbody>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>
A much simpler solution:
t = $('table#tbl2')
firstTr = t.find('tr:first').remove()
firstTr.find('td').contents().unwrap().wrap('<th>')
t.prepend($('<thead></thead>').append(firstTr))
table thead tr th {
background: green;
}
table tbody tr td {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl1"><tbody><tr><td>Name</td><td>Age</td></tr><tr><td>Ron</td><td>28</td></tr></tbody></table>
<br /><br />
<table id="tbl2"><tbody><tr><td>Name</td><td>Age</td></tr><tr><td>Ron</td><td>28</td></tr></tbody></table>
Here is the explanation of the code:
Remove the first tr element from the dom.
Find the td elements, take their contents() and unwrap the td.
Wrap each of the contents() of the td with th tag.
Add the <thead> tag to table and append the tr we worked on to the thead
You can make:
$('table').prepend('<thead></thead>'); // Add thead
$('table tr:eq(0)').prependTo('table thead'); // move first tr to thead
$('table thead').html(function(id, html) { // you might use callback to set html in jquery
return html.replace(/td>/g, 'th>'); // replace td by th
// use regExp to replace all
});
When you use .prependTo, this move the element to another in top and you might use callback in .html function in jquery.
Reference:
http://api.jquery.com/prependto/
http://api.jquery.com/appendto/
Years passed (so no jQuery anymore), and I want to do this and have solved it like this. The idea is 1) get the first row(<tr>), 2) replace every <td> tags on the first row to <th>.
const txt = `<table>
<tbody>
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>`;
const el = document.createElement('table');
el.innerHTML = txt;
[...el.querySelector('tr').querySelectorAll('td')].forEach(td =>
td.outerHTML = td.outerHTML
.replace(/<td([^>]*)>/, '<th$1>')
.replace(/<\/td>/, '</th>')
);
console.log(el.outerHTML);
/*
<table>
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Ron</td>
<td>28</td>
</tr>
</tbody>
</table>
*/

Dynamically adding rows to a table

I'm trying to dynamically add a <tr> with two <td>s into a <table> via javascript, but my fiddle doesn't seem to do anything, does anyone see the problem?
Fiddle: https://jsfiddle.net/otL69Lpo/2/
HTML:
<button type="button" onclick="myFunction()">Click Me!</button>
<table class="table table-bordered" id="chatHistoryTable">
<tr>
<td>
12:30:30
</td>
<td>
text here
</td>
</table>
JS:
function myFunction() {
var table = document.getElementById("chatHistoryTable");
var tr = document.createElement("tr");
var td = document.createElement("td");
var td2 = document.createElement("td");
var txt = document.createTextNode("TIMESTAMP");
var txt2 = document.createTextNode("user: text");
td.appendChild(txt);
td2.appendChild(txt2);
tr.appendChild(td);
tr.appendChild(td2);
table.appendChild(tr);
}
Output should be as:
| TIMESTAMP | user: text |
This is a common issue in jsFiddle. There are several options for how to load the JS and you'll need to change the loading to either:
No wrap - in <head>
No wrap - in <body>

How to include multiple td into the tr?

I just wanted to append td in the tr
Table
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dave Gamache</td>
<td>26</td>
<td>Male</td>
</tr>
</tbody>
</table>
Script
// Receive Message
socket.on('message', function(data){
console.log(data);
var Project = data.project;
var Id = data.id;
var Event = data.event;
var tr = document.createElement("tr");
var td1 = tr.appendChild(document.createElement('td'));
var td2 = tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
td1.innerHTML = Project;
td2.innerHTML = Id;
td3.innerHTML = Event;
document.getElementById("result").appendChild(td1, td2, td3);
});
I come up with this above code but this is not working means see the image...
The last line is wrong. You should append the tr to the table, not all the tds.
document.getElementById("result").appendChild(tr);
document.getElementById("result").appendChild(td1, td2, td3);
seems you are appending your tds directly to the table, not a tr in the tbody.
Try this way to bind your data
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody id="bodytable">
</tbody>
</table>
socket.on('message', function(data){
console.log(data);
var _html='';
html +='<tr>'
html +='<td>'+data.project+'</td>';
html +='<td>'+data.id+'</td>';
html +='<td>'+data.event+'</td></tr>';
$('#bodytable').append(_html);
});

Javascript add Row, one function for different tables

I have a few tables like this
<table id="table_1">
<tr>
<td><input type="text" name="date[]"</td>
</tr>
</table>
the number of the <td>'s is very variable.
Currently I'm using a function like this:
function addRow(){
var table = document.getElementById('table_1');
var row = table.insertRow(-1);
var cell1 = row.insertCell(0)
....
cell1.innerHTML="<input type='text' name='date[]' />
}
using this method, it would require a custom function for every type of table.
Is there a way, to add a Line to a table, which is exactly the same as the last row?
In a table with 7 cells, 7 cells would be added, with the right content.
Is this possible in pure JS?
You could do it this way with jQuery:
Edit:
Sorry, I did not see you wanted pure JS.
jQuery
$('button').click(function(){
var table = $(this).prev('table');
var lastrow = $('tr:last-child', table).html();
table.append('<tr>' + lastrow + '</tr>');
});
HTML
<table>
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<button>Add a row</button>
<table>
<tr>
<th>Meal</th>
<th>Price</th>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<button>Add a row</button>
JS Fiddle Demo
Maybe this is what you need : http://jsfiddle.net/thecbuilder/bx326s31/1/
<input type="button" onclick="cloneRow()" value="Clone Row" />
<input type="button" onclick="createRow()" value="Create Row" />
<table>
<tbody id="tableToModify">
<tr id="rowToClone">
<td><input type="text" name="txt[]"/></td>
<td>bar</td>
</tr>
</tbody>
</table>
function cloneRow() {
var row = document.getElementById("rowToClone"); // find row to copy
var table = document.getElementById("tableToModify"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function createRow() {
var row = document.createElement('tr'); // create row node
var col = document.createElement('td'); // create column node
var col2 = document.createElement('td'); // create second column node
row.appendChild(col); // append first column to row
row.appendChild(col2); // append second column to row
col.innerHTML = "qwe"; // put data in first column
col2.innerHTML = "rty"; // put data in second column
var table = document.getElementById("tableToModify"); // find table to append to
table.appendChild(row); // append row to table
}
Refer : https://stackoverflow.com/a/1728578/3603806

Categories

Resources