How to insert HTMLTableRowElement into a Table Body? - javascript

I've taken a look at table and table body methods, and it does not mention how to insert a HTMLTableRowElement. Anyone know a nice way to insert a HTMLTableRowElement into the table body?
const tbody = document.getElementsByTagName('tbody')[0];
// Only inserts an empty row
// Want to insert a HTMLTableRowElement that I've parsed using jsdom
tbody.insertRow();
EDIT:
With guidance #frontend_dev, it looks like jsdom is not using native DOM elements. So the solution may look something like the follow:
let rows_rep = '';
jsdom.env(html_with_tr, function(err, w) {
rows_rep = w.document.getElementsByTagName('tr')[0].outerHTML;
}
const tbody = document.getElementsByTagName('tbody')[0];
const newRow = tbody.insertRow();
newRow.innerHTML = rows_rep;

Given an HTML string containing the row you want to add, you can get that row without jsdom and append it to a table in the current document:
// Sample HTML string:
var html = `<html>
<body>
<h1>my title</h1>
<table><tr><td>dynamicly added row</td></tr></table>
<p>other text in here</p>
</body>
</html>`;
// Create in-memory element and load HTML into it:
var span = document.createElement('span');
span.innerHTML = html;
// Get the row element out of it, and append it:
var tr = span.querySelector('tr');
var tbody = document.querySelector('tbody');
tbody.appendChild(tr);
<table border=1>
<tr><td>existing row</td></tr>
</table>

Related

Append child can`t add more than 1 child node

var data={
1:"dasf",
2:"jlla",
3:"jalf"
};
(function () {
var table=document.createElement("table");
var tr=document.createElement("tr");
for(var i in data){
tr.innerText=data[i];
(function(){
table.appendChild(tr);
console.log("in"+tr.innerText)
})();
console.log("out"+table);
}
})();
it always shows different and changes everytime,guessing the time appendchild happenes is not simply following?
You only create one tr element.
Each time you append it, you move it from where it was in the DOM and put it in the new location.
If you want to create a new table row for each item in data, then you need to move your createElement call inside the loop.
(You also need to change how you are adding content to it, a tr element isn't allowed to contain text directly, and if you aren't putting multiple data cells in each row, you should probably be using a list instead of a table in the first place).
See this snippet code for creating table
I have edited your code
<div id="wrap"></div>
<script>
var data={
1:"dasf",
2:"jlla",
3:"jalf"
};
(function () {
var table=document.createElement("table");
var tr;
var td;
for(var i in data){
tr=document.createElement("tr");
td=document.createElement("td");
td.innerText = data[i];
tr.appendChild(td);
table.appendChild(tr);
}
document.getElementById("wrap").appendChild(table)
})();
</script>
This will be the output table:
<table>
<tr>
<td>dasf</td>
</tr>
<tr>
<td>jlla</td>
</tr>
<tr>
<td>jalf</td>
</tr>
</table>

Write HTML to screen with Javascript function

I'm very new to JavaScript and HTML I and need some help!
I'm trying to write a table in JavaScript, that writes into the page HTML, and then importing that function to a HTML file to show the table.
I have this in a JavaScript file
function createTable()
{
var table = "<table>";
table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";
document.write(table);
}
And then I specify the src and call the function in a html file like so:
<head>
<script scr = "source/file.js" type=text/javascript"></script>
</head>
<body>
<script>
createTable()
</script>
</body>
Although this works, I've heard that using document.write() is a very bad practice.
I have tried using table = document.getElementById('tablePrint').innerHTML; and then in the HTML file used <div id="tablePrint"></div> however my table doesn't show. I've also tried document.body.appendChild(table); but that doesn't work either.
Is using document.write() ok? Or is their a better way to write my table to the HTML on screen.
You are missing some double quotes in your example. I'd suggest you to use JQuery:
$(function() { // After the HTML content loads
var table = "<table>";
table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";
$('body').append(table); // Appends HTML to an element
});
Here is the fiddle.
And here is why document.write() is not a good practice
The write() method is mostly used for testing: If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Hope it helped :)
The HTML <center> element is obsolete since 1999 when HTML 4 came out. It's abolutely amazing that people (amateurs?) are still trying to use it. Let me cite from the Mozilla article:
This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the CSS text-align property, which can be applied to the <div> element or to an individual <p>. For centering blocks, use other CSS properties like margin-left and margin-right and set them to auto (or set margin to 0 auto).
Normally, we don't use document.write for creating HTML content since it does not allow to control where the content is inserted. Rather, we use suitable DOM attributes (such as innerHTML) and methods (such as appendChild).
The proper way of creating an HTML table and inserting it into the HTML body element is using the DOM methods insertRow and insertCell, as in the following code example:
function createTable() {
var i=0, rowEl=null,
tableEl = document.createElement("table");
// create 10 table rows, each with two cells
for (i=1; i <= 10; i++) {
rowEl = tableEl.insertRow(); // DOM method for creating table rows
rowEl.insertCell().textContent = "table cell "+ i +"-1" ;
rowEl.insertCell().textContent = "table cell "+ i +"-2" ;
}
document.body.appendChild( tableEl);
}
The document.write() method for this purpose is not preferred. The most preferred way to do this with pure JavaScript is to use the appendChild() method.
Try this :
var table = document.createElement("table"); //Creating the <table> element
var tr1 = document.createElement("tr"); //Creating the first <tr> element
var tr2 = document.createElement("tr"); //Creating the second <tr> element
var th = document.createElement("th"); //Creating a <th> element
var td = document.createElement("td"); //Creating a <td> element
var text1 = document.createTextNode("Title"); //Creating the content of <th>
var text2 = document.createTextNode("data"); //Creating the content of <Ttd element
document.body.appendChild(table); //The <body> is adopting the <table>
table.appendChild(tr1); //The <table> is adopting the first <tr>
tr1.appendChild(th); //The first <tr> is adopting the <th>
table.appendChild(tr2); //The <table> is adopting the second <tr>
tr2.appendChild(td); //The second <tr> is adopting the <td>
th.appendChild(text1); //<th> is adopting its content
td.appendChild(text2); //<td> is adopting its content
<center> tag is deprecated now, don't use it, use CSS instead.
Working demo
Have your function return the table as a string.
function createTable()
{
var table = "<table>";
table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";
return table;
}
Assuming you don't want to overwrite the body completely create a div have it styled the way you want and just add the table content there.
<body>
<div id="table"></div>
<script>
var table=createTable();
document.getElementById("table").innerHTML=table;
</script>
</body>

Best way to add row to HTML table without re-rendering

I am using websockets (socket.io) for real-time stuff, and it may be that a new item is added to a collection which I would like to then add to the screen. Is there a good way to add a row to an HTML table without re-rendering the whole view?
You can use insertRow on that table. Here is an example:
<table id="TableA">
<tr>
<td>Old top row</td>
</tr>
</table>
<script type="text/javascript">
function addRow(tableID) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New top row');
newCell.appendChild(newText);
}
// Call addRow() with the ID of a table
addRow('TableA');
</script>
Example taken from the Mozilla page for insertRow.

Javascript, creating a template for a textfield with subscript and superscript

I am rather new to JavaScript. In my experimentation with some sample code, I have created an html file which contains a table. In one of the table data fields I have a text type field. Is there a way to make a button that inserts a pre-defined template for entry that allows for manipulation? aka I press a button "money" that inputs an additional formatted text to "$0.00".
so for example
function input_button(){
var template = "$0.00"
var my_txt = document.getElementById("money");
my_txt.value += Template;
On a side note, what if I wanted to use subscript and superscript? I have tried utilizing the .sup() and .sub() methods, but it just inserts the tags and doesn't alter the aesthetics of the text. ( so in the table, it looks like
<sub> things to be subscript </sub>
opposed to
things to be subscript
I'm not familiar with any way to template text formats, so you might just have to hard code in the logic. As to your second question, when you use the .sup and .sub methods, are you inserting the result in the inner html? For example:
function helloWorldSuper(){
var str = "Hello World";
var result = str.sup();
document.getElementById("tableCell").innerHTML = result;
}
To apply a mask to the input field in order to auto-format values with a template you will need to listen to input key press events and handle according to your mask. There are some scripts that already do this, like Masked Input Plugin for jQuery.
If you want the input text to just have $0.00 as an initial value, it's quite easy to do.
You can create and insert a row into the table via JavaScript like this:
<html>
<body>
<button id="insertRowButton">Insert</button>
<table>
<thead>
<tr><th>Text</th><th>Input</th></tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<script>
(function() {
// Elements used
var tableBody = document.getElementById('tableBody'),
insertRowButton = document.getElementById('insertRowButton');
// Create a new row template
function createRow() {
var tr = document.createElement('tr'),
tdText = document.createElement('td'),
tdInput = document.createElement('td'),
sub = document.createElement('sub'),
input = document.createElement('input'),
text = document.createTextNode('This is a text node '),
subscriptText = document.createTextNode('with subscript');
sub.appendChild(subscriptText);
tdText.appendChild(text);
tdText.appendChild(sub);
input.value = '$0.00';
tdInput.appendChild(input);
tr.appendChild(tdText);
tr.appendChild(tdInput);
return tr;
}
// Insert a new row into table
function insertRow() {
var tr = createRow();
tableBody.appendChild(tr);
}
// Bind events
insertRowButton.addEventListener('click', insertRow);
}());
</script>
</body>
</html>
Here is it at JSFiddle: http://jsfiddle.net/ck7qargw/
I'm a little confused but I'm making the assumption that you are trying to add sup/sub script via innerHTML?
var template = "<span class='supStyle'>$0.00</span>"
CSS:
.supStyle{vertical-align:top;font-size:smaller;}
Or, you can use a forloop:
mySup = document.getElementsByClassName("supStyle");
for (var i=0;i<mySup.length;i++)
{
mySup[i].style.verticalAlign = "sub";
mySup[i].style.fontSize = "smaller";
}

Dynamically appending a row by cloning an existing row?

I have a row in a table and that row is not displayed as css style is set to display:none .
HTML table:
<table class="myTable">
<tr class="prototype">
........
</tr>
</table>
CSS code:
.myTable .prototype{display:none;}
Now i have to clone the same row and add some data to it and append the row to the table as below: i have below jquery code:
var master = $(this).parents("table.myTable");
var prot = master.find(".prototype").clone();
prot.attr("class", "");
prot.find("#attributeValue").attr("value", "ABC");
prot.find("#contactFirstName").attr("value", "XYZ");
jQuery('table.myTable tr:last').before(prot);
But the row won'ttbe added to the table. Please help me.
Thanks!
If you run the code in the onLoad event, change the first line to var master = $(this).find("table.myTable"); or var master = $("table.myTable");
Use prot.removeClass(); instead of prot.attr("class", "");
Ids have to be unique, if elements in your prototype-row have an id you get invalid HTML.
Use $().val('ABC') instead of $().attr('value', 'ABC')
If it still doesn't work, please show more code (maybe a jsfiddle).
var master = $(this).parents("table.myTable");
var prot = master.find("tr.prototype").clone();
prot.removeClass('prototype');
prot.find("#attributeValue").val("ABC");
prot.find("#contactFirstName").val("XYZ");
master.append(prot);
prot.show();

Categories

Resources