I'm pretty new to Javascript. I just have a basic question. Can somebody tell me why executing the javascript code in the JSFiddle link below results in this error:" Cannot read property 'innerHTML' of null".
Link:
http://jsfiddle.net/ali89ma/tz5h8umk
var myTable = document.createElement("TABLE");
var row1 = myTable.insertRow(-1);
var cell1 = row1.insertCell(-1);
cell1.innerHTML = "23.00";
cell1.id = "1000price";
var cell1Content = document.getElementById("1000price").innerHTML;
console.log(cell1Content);
But if I write the line below it works fine.
var cell1Content = cell1.innerHTML;
console.log(cell1Content);
Thanks.
as mentioned above The getElementById() method returns the element that has the ID attribute from the DOM with the specified value.
you create a table element dynamiclly but you didnt append it to your page(this will add the table to the DOM elements)
so you need to add this append order to your code like that :
// create a table element dynamiccly but it still not in the DOM elements
var myTable = document.createElement("TABLE");
var row1 = myTable.insertRow(-1);
var cell1 = row1.insertCell(-1);
cell1.innerHTML = "23.00";
cell1.id = "1000price";
//the next line will add your table to the DOM
document.body.appendChild( myTable );
//now you can use the getElementById method to get elements from the DOM
var cell1Content = document.getElementById("1000price").innerHTML;
console.log(cell1Content);
insertCell returns null if the parent table does not exist in the DOM.
Add this line immediately after line 1:
var myTable = document.createElement("TABLE");
document.body.appendChild( myTable ); // <-- this line
var row1 = myTable.insertRow(-1);
After adding the line it works and I get "23.00" output in my console.
You must append element after create
var myTable = document.createElement("TABLE");
document.body.appendChild(myTable);
You are creating the table through javascript. When you are trying to access the table element it will not be present in the DOM. You need to add the table to the DOM then it will work. Add this line able the var cell1Content
document.body.append(myTable);
append table in body before accessing element
var myTable = document.createElement("TABLE");
document.body.appendChild(myTable);
working fiddle
http://jsfiddle.net/tz5h8umk/2/
Related
I've tried with a stupid way of inserting code for a new table, but not even that seems to work. What would be the proper way?
Here's what I tried to do:
var table = document.getElementsByClassName("test")
[0].getElementsByClassName("tableclass");
for (var i = 0, l = table.length; i < l; i++) {
var content = table[i];
let s = content.innerHTML;
s = s.replace(/table/g, 'table border="1"');
s = s.replace(/tr>[\s\S]*?<tr>[\s\S]*?<td>3/g, 'tr>\r\n<tr>\r\n<td>3');
content.innerHTML = s;
}
And a fiddle: https://jsfiddle.net/d10tk7nr/1/
Also, the reason my stupid way doesn't contain the whole table is because some of the cells where I want to eventually use this would contain random data and I don't know how to skip that.
If you want to create a new HTML-Element, every browser got you covered on that.
var tr = document.createElement('tr');
console.log(tr);
The browser console will show you exactly what you have created - a new HTML element that is not yet part of the DOM:
<tr></tr>
The same goes with the creation of some content for that table row:
var td1 = document.createElement('td'),
td2 = document.createElement('td');
td1.innerText = '5';
td2.innerText = '6';
console.log(td1, td2);
The result will be two td-elements:
<td>5</td> <td>6</td>
Now we have to glue these parts together. Browsers will also have you coverd on this:
tr.append(td1);
tr.append(td2);
console.log(tr);
The result is a complete table row:
<tr><td>5</td><td>6</td></tr>
All we have to do is append this row to your table:
var table = document.querySelector('.test table tbody');
table.append(tr);
The elements you have created are now part of the DOM - child elements of the body of your table to be excact.
Click here for a fiddle
Edit
If you want to insert the new row to a specific place, you have to find the element you that should be next to it and use insertBefore. This would change the the last piece of code to:
var targetTr = document.querySelector('.test table tr:nth-child(2)');
targetTr.parentNode.insertBefore(tr, targetTr);
If you want to choose where to put your new row within your javascript, you can use the childNodes property:
console.log(table.childNodes);
I'd use insertAdjacentHTML, like so:
table[i].insertAdjacentHTML('beforeend', '<tr><td>5</td><td>6</td></tr>');
Please see this fiddle: https://jsfiddle.net/52axLsfn/4/
Also demonstrates how to set the border. Note that this code targets all tables, so depending on your situation you may want to be more specific.
In order to make my code concise and reduce unnecessary dom rendering, I'm trying to construct and populate a table before appending it to the document. The problem I'm having is that only the divs are getting appended to the table, so I end up with a table full of divs instead of tr's with td's that contain divs.
I'm pretty sure this is because when I use the .appendTo function it's not appending the td to the tr, and the tr to the table but instead is removing the div and appending it to each in turn, lastly ending up in the table.
How can I construct a node chain before appending to the document?
Code:
var playerSelect = $( "#playerSelect" );
var playerElements = [];
var rowCounter = 0;
var playerTable = $("<table/>").attr("id", "playerTable");
for (player in playerBase){
var playerDiv = $("<div/>").addClass("player").text(player + playerBase[player].rating);
playerDiv.appendTo("<td/>").appendTo("<tr/>").appendTo(playerTable);
};
playerSelect.append( playerTable );
.appendTo() does not accept a string value. $() does however, so you could change your code like this:
$("<tr />").append($("<td />").append(playerDiv)).appendTo(playerTable);
That said, this is not the cleanest way to do it, you might want to have a look at templating engines if you have a lot of these structures in your code.
for (player in playerBase){
var tr = $('<tr/>');
var td = $('<td/>');
td.appendTo(tr);
var playerDiv = $("<div/>").addClass("player").text(player + playerBase[player].rating);
playerDiv.appendTo(td);
tr.appendTo(playerTable);
};
I have a table like this.
<table id='table1'>
</table>
and in this table i am dynamically adding rows to the table using jquery like below.
var tbl = $("#table1");
tbl.append('<tr></tr><tr></tr><tr></tr>');
I can add class to the appended rows using 2 methods like below
case 1
tbl.find('tr').eq(0).addClass("test");
tbl.find('tr').eq(1).addClass("test");
or case 2
for (var i=0;i<tbl.find('tr').length;i++) {
tbl.find('tr').eq(i).addClass("test")
}
and my question is there any way i can add same classname to the dynamically appended rows. Answers expecting in jquery. Thanks in advance.
Once an element is added to the DOM, you have no way of telling if it was dynamically added or not unless you have custom code that does such. I would suggest changing .append to .appendTo so you have access to the rows you're adding and can call .addClass:
var tbl = $("#table1");
$('<tr></tr><tr></tr><tr></tr>').appendTo(tbl).addClass("test")
You could also put the class in the string then append it or modify it (add a class) prior to appending it. Note how I only have one tr in my string but append it multiple times (optionally adding a class as noted)
var tbl = $("#table1");
var tr = '<tr class="test"></tr>';
var td = '<td class="test">new data</td>';
//var addedrow = $(tr).append(td).addClass("newclass");//adds class to the row
var addedrow = $(tr).append(td);//create new row object
addedrow.find('td').addClass("newclass"); //adds class to the td in the new row
var ar2 = $(tr).append(td);
var ar3 = $(tr).append(td);
tbl.append(addedrow, [ar2, ar3]); // appends the new rows
tbl.find('tr').last(td).addClass("newclass");//add class to last rows td
see it in action here: http://jsfiddle.net/MarkSchultheiss/0osLfef3/
I want to get all the child elements from the row.
Javascript:
var table = document.getElementById("tableID");
var row = table.getElementsByTagName("tr")[0];
The corresponding HTML is
:
:
:
var tab = document.getElementById("tableID");
var Row = tab.getElementsByTagName("tr")[0];
when Intry to get Row.cells IE8 returns undefined.If I use this code locally It works fine.But Am using xsl code.
This
var table = document.getElementById("tableID");
Returns your actual tr.
So for it to be ok you should do:
var row = table.getElementsByTagName("td")[0];
Use querySelectorAll (see MDN). It'll even work in IE8:
var cells = document.querySelectorAll('#tableID td');
I think I know this is an IE bug ...
I need to add new row to an HTML table at the exact position.
(don't want insertRow(index) cuz this looks like gonna be better for some other reasons)
function AddNewItem(td) { ///td comes from button at the HTML code, <input ... onclick="AddNewItem(this.parentNode)"
var grid = GetGrid();
var itemIndex = $(td.parentNode).attr('index');
///alert(itemIndex + "'e eklenecek");
var newRow = document.createElement('tr');
var td1 = document.createElement('td');$(td1).addClass('td');
var td2 = document.createElement('td');$(td2).addClass('td text r');
var td3 = document.createElement('td');$(td3).addClass('td text r');
var td4 = document.createElement('td');$(td4).addClass('td text r');
$(newRow).append(td1);$(newRow).append(td2);$(newRow).append(td3);$(newRow).append(td4);
grid.insertBefore(newRow, td.parentNode); ///THIS GIVES AN INVALIDARGUMENT error .. Any solutions will be appreciated :)
}
function GetGrid() {
var grid = document.getElementById("MasterTableView");
return grid;
}
My guess is that td.parentNode is not a child element of grid. Take a look at the W3C specification for insertBefore to make sure that you are calling the method with valid parameters.
I would guess that you're passing in an invalid argument to AddNewItem, that (in IE, at least) it's not a td element like you think.