How to use createElement to create a new table? - javascript

Why the following code doesn't work?
<html>
<head>
<script type="text/javascript">
function addTable() {
var table = document.createElement('table');
table.innerHTML = "<tr><td>123</td><td>456</td></tr>";
document.getElementById("addtable").appendChild(table);
}
</script>
</head>
<body>
<input type="submit" value="New Table" onClick="addTable()"/>
<div id="addtable"></div>
</body>
</html>

To the best of my knowledge, setting the innerHTML property of a table element or table section element (like tbody or thead) does not work on Internet Explorer (EDIT: I just checked - with ietester and plain IE8. Result is "unknown runtime error" for IE6 and IE8, and it crashes IE7 but that might be an IEtester specific problem).
The DOM standard way of adding rows to a table is using the insertRow() method on a table or table section element (look for HTMLTableElement and HTMLTableSectionElement in that DOM spec) :
<script type="text/javascript">
function addTable() {
var c, r, t;
t = document.createElement('table');
r = t.insertRow(0);
c = r.insertCell(0);
c.innerHTML = 123;
c = r.insertCell(1);
c.innerHTML = 456;
document.getElementById("addtable").appendChild(t);
}
</script>
In the script, there is no explicit table section being created. AFAIK, a TBODY is automatically created, and rows are inserted in there.
EDIT: regarding IE, I should point out that you can add a table with content and all by setting the innerHTML property, but the html you inject in there must be a complete table. So this does work, even on IE:
<script type="text/javascript">
function addTable() {
var html = "<table><tr><td>123</td><td>456</td></tr></table>";
document.getElementById("addtable").innerHTML = html;
}
</script>

//_table my current table
var table = document.createElement('table'); //new table
table.innerHTML = _table.innerHTML; //clone table innerHTML

Related

How to apply style sheets to dynamically created elements?

this should be an easy one: I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var table = document.createElement("table");
table.setAttribute("id","table");
var headRow = document.createElement("tr");
var dataRow = document.createElement("tr");
var head = document.createElement("th");
var data = document.createElement("td");
head.innerHTML="head";
data.innerHTML="data";
headRow.appendChild(head);
dataRow.appendChild(data);
table.appendChild(headRow);
table.appendChild(dataRow);
console.log(document.styleSheets);
table.className = "table";
document.getElementById("test").appendChild(table);
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
The problem is: The style specified in the bootstrap.min for the class "table" is never applied upon loading the side. Do I have to do something additionally? I test it in the most recent version of Safari.
Any Help?
Cheers Twerp
It is not dynamically created issue. It is because you haven't set the class to table. As Bootstrap Docs says:
You have to use <thead> and <tbody> for the class to work.
To add in your answer:
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Add this for a quick fix:
$("tr:first-child").wrap("<thead/>");
Your final code should look like:
var table = document.createElement("table");
table.setAttribute("id","table");
var headRow = document.createElement("tr");
var dataRow = document.createElement("tr");
var head = document.createElement("th");
var data = document.createElement("td");
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
head.innerHTML="head";
data.innerHTML="data";
headRow.appendChild(head);
dataRow.appendChild(data);
table.appendChild(thead);
table.appendChild(tbody);
console.log(document.styleSheets);
table.className = "table";
document.getElementById("test").appendChild(table);
The slight difference in styling is because Bootstrap relies on the <tbody> and <thead> elements to apply styling. If you're dynamically creating elements, you need to create these too:
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Then, instead of appending headRow and dataRow directly, append the newly created elements:
table.appendChild(thead);
table.appendChild(tbody);
Example Fiddle
$(function () {
var table = $('<table></table>').attr('id', 'table').addClass('table')
var head = $('<th></th>').html('head')
var data = $('<th></th>').html('data')
var headRow = $('<tr></tr>').append(head)
var dataRow = $('<tr></tr>').append(data)
table.append(headRow)
table.append(dataRow)
console.log(document.styleSheets);
$('#test').append(table);
})
Best way to add style sheet to dynamically added content is to use classList
Please refer below link:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
OR
You can use element.style.cssProperty

element.length returns 0 even if the element exist

The code below will dynamically create 5 table rows. I dont understand why td.length returns 0 even though I already created it. Can someone explains to me why?
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
var table = $("#mytable");
for(var c=1; c<6; c++){
var id = "#row" + c;
var tr = $("<tr><td id="+id+">Row "+c+"</td></tr>");
table.append(tr);
}
var td = $("#row1");
alert(td.length);
});
</script>
</head>
<body>
<table id="mytable">
</table>
</body>
</html>
The id value itself should not contain the #.
Change this:
var id = "#row" + c;
to this:
var id = "row" + c;
The selector that you use with jQuery contains the #, but not the id value itself.

Create a JavaScript spreadsheet based on input

I am trying to learn web programming and Javascript.
I'm trying to take whatever the user copied from an Excel spreadsheet and create a JavaScript spreadsheet/table that includes dropdowns out of it.
So basically the user would paste the input into a blank field, press the submit button, and JavaScript would generate an Excel-like spreadsheet which would have the data sorted accordingly. The dropdowns would be at the top of each column and allow the user to select either ready/not ready. This is being designed for a confluence WIKI page.
This is what I have so far, right now the code parses the input-field and creates a multi-dimensional array. After that, the array will be logged on the console. I need help getting everything displayed on the wiki page.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<textarea id="textarea"></textarea>
<button id="loadPaste">parse</button>
<script type="text/javascript">
var excel = new Array();
$(document).ready(function() {
$('#loadPaste').click(function() {
var text = $('#textarea').val();
var rows = text.split("\n");
for (var i = 0; i < rows.length; i++) {
excel[i] = rows[i].split("\t");
}
console.log(excel);
});
});
</script>
</body>
</html>
Lets close this one: //THIS IS #Downgoat response with little explanation about xml parser.
use an xml parser var xml = (new DOMParser()).parseFromString($('#textarea').val(), 'text/xml')
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
<html>
<body>
<p id="demo"></p>
</body>
</html>

html script variable assignment

So I have a script block:
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
I'm still quite green to javascript. But is there a way to assign the value of a variable in a script block to a HTML element like input type? I know that the code is unreachable.
hope it will help you to understand how javascript work
<html>
<head>
<script>
var totalPopulation = 0;
function addAndShowPopulation(population) {
totalPopulation = totalPopulation + population;
var input_tag = getTag('my_input_id');
input_tag.value = totalPopulation;
}
function startAdding() {
addAndShowPopulation(10);
setTimeout( function(){startAdding();},1000);
}
function getTag(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="startAdding();">
<div>
<input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
</div>
</body>
</html>
Yes, you just have to give an id to the input, for instance "id = my_input_id";
Then, in the javascript, just write :
$("my_input_id").value=totalPopulation;
That's how ajax works: find html elements ids and fill them dinamically using javascript values.
Just be carefull that the html in read before the JS. If not, $("my_input_id") will return Null
More so, you need to do something like this:
<tr>
<td>
<input type="text" id="censusPop" name="censusPop" value=""/>
<td>
<tr>
<!-- Other stuff -->
<script>
var totalPopulation = 10;
// or for loop, or whatever here.
var censusText = document.getElementById('censusPop');
censusText.value = totalPopulation;
</script>
</body>
HTML and JavaScript can interact, but not directly like that. The best thing to do is use <script> tags to setup code that updates the browser DOM. By putting the <script> tags after the HTML, usually at the bottom of the <body> tag, you allow the browser a chance to create the elements before you actually try to use them.
Another note: <tr> tags should contain <td> tags, it's the difference between a row and a column.
If you need to do multiple DOM manipulations, I'd suggest using jQuery is the proper way.
<tr>
<input id="censusPop" type="text" name"censusPop" value=""/>
</tr>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// make sure, the code is executed when the DOM is ready
$(function () {
// grab the input element by its ID
var $input = $('#censusPop'),
totalPopulation = 0;
// do your population calculations
totalPopulation = ....;
// assign the value to the input element
$input.val(totalPopulation);
});
</script>

inserting td in a tr with ID using javascript

I have to insert a td inside a tr which has a ID using javascript.Can someone please help me or guide me in the right direction.Sorry it might be simple but I m very new to javascript.
<html>
<head>
<script type="text/javascript">
function insertText ()
{
//function to insert any text on the tr with id "tr1"
}
</script>
</head>
<body onload="javascript:insertText()">
<table>
<tr id="tr1">
</tr>`
</table>
</body>
</html>
function insertText ()
{
var td = document.getElementById('tr1').insertCell(0);
td.innerHTML = "Some Text";
}
The main advantage of insertCell (and insertRow) is that they allow you to specify an index where the new cell (or row) is to be inserted.
Try this:
function insertText ()
{
var el = document.createElement('td');
el.innerHTML = 'Hello World';
document.getElementById("tr1").appendChild(el);
}

Categories