Javascript replace child? - javascript

I have a table in HTML with a few rows.
I originally gave some of those table rows (TR) an ID and I would use javascript to set the INNERHTML of some of these table rows with some new dynamic content.
However, Internet Explorer doesn't like this and gives an 'unknown runtime error' because I am trying to set the INNERHTML of an inline element.
So now, I'm attempting to instead replace the entire table row child with a new one. I can't simply appendChild because I need the new table row to be in the same position as the original (to imitate as if just this table row's content had been changed when in reality, the entire row is being 'replaced').
Was hoping someone had a solution to this (I was thinking a) get child position b) delete original table row and c) insert new table row at child position found in A). Perhaps there is even an easier and better solution? Would love some input.
Cheers!

IE doesn't much like table manipulation via innerHTML. You can do this:
var oldrow = document.getElementById('the_id');
var newrow = document.createElement('tr');
// add cells to the new row
var newcell = document.createElement('td');
newcell.innerHTML = "content";
newrow.appendChild(newcell);
// ... ... ...
// Replace the old row with the new one:
oldrow.parentNode.insertBefore(newrow, oldrow);
oldrow.parentNode.removeChild(oldrow);
newrow.id = 'the_id';
Off-topic: Issues like this are part of why I usually recommend using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over browser oddities and provide additional basic functionality that the DOM itself doesn't give you. This lets you focus on the actual problem you're solving, rather than the arcana of browser pitfalls.

It's innerHTML, not INNERHTML.

Decided to append a child row AFTER the current row, and delete the old row. Most efficient method I could think of.

Related

Performance issues with appendTo() to create tables dynamically

After debugging my tables seemed to load slow (I assumed it was my server), I found that it was actually the front-end javascript, not the backend PHP. The server is responding in 3-4ms while the javascript handling is taking up to 350ms.
After reading this article, I found the culprit:
Article snippet:
var arr = reallyLongArray;
$.each(arr, function(count, item) {
var newTd = $('<td></td>').html(item).attr('name','pieTD');
var newTr = $('<tr></tr>');
newTr.append(newTd);
$('table').append(newTr);
});
The difference is I am using appendTo() instead of append. This is because my rows have dynamic jquery elements to them - click handlers, .data(), etc.
The solution in the article is basically to concatenate your rows and then run one .append() at the end instead of one for each row.
Is there a similar solution for appendTo()? Perhaps appending to some sort of ghost element and then inserting the whole element at the end? Would this increase performance?
Perhaps appending to some sort of ghost element and then inserting the whole element at the end?
Exactly. You can create your rows and append them to a disconnected tbody element, then append that tbody element to your table. That way there's a single live DOM manipulation, not hundreds of them.

Assign and retrieve an html table to a javascript variable with jQuery

I want to backup an html table to afterwards filter it using jquery:
$('.row').closest('td').not(':contains(' + v + ')').parent('tr').remove();
Since I do remove() I have to back up the rows before:
var allTable = $('#mytable').html();
And then, when filter is performed I turn back to previous table data:
$('#mytable').html($(allTable));
But this does not work. If I do:
alert($(allTable).filter('tr').length);
next to the first assignment, zero rows are returned.
Please, can you assist me?
filter() is used to find elements within an array of elements. This isn't what you need. You're looking to find() the child elements within another. Also, storing the HTML only to turn it back in to a jQuery object is a little redundant - you may as well just store the jQuery object itself. Try this:
var $table = $('#mytable');
$table.remove(); // use your existing logic here
alert($table.find('tr').length);
$table.appendTo('body'); // add the table back in to the DOM when conditions are met
Example fiddle
I ran into a similar issue when using a highlight function. I solved it by cloning the table into a hidden div and restoring it from there, instead of from a variable. see jquery highlight() breaking in dynamic table
Did you solve this problem?
I suggest a workaround.
Instead of using your cloned table, make a (temporary) copy of it and use it for alert.
var alertTable = allTable;
alert($(alertTable).filter('tr').length);

Nested_form inside table rows

I'm using nested_form inside one of my Rails forms. I saw you can generate tr 's instead of of div 's using this article https://github.com/ryanb/nested_form/wiki/How-To:-Render-nested-fields-inside-a-table
Where would the javascript go though that they suggest?
window.nestedFormEvents.insertFields = function(content, assoc, link) {
var $tr = $(link).closest('tr');
return $(content).insertBefore($tr);
}
First of all, its not like "you can generate TR 's instead of of DIV". The link says that you can disable inserting DIVs. And you can add the td, tr explicitly. Like in the link they added td and tr in their form.
And sometimes you create forms by javascript and by default those fields are also wrapped with DIV. But you can change the behavior by using that javascript snippet. It will override the corresponding method with this new one.
Let me know if I could clear up your confusions.

Remove rows from an HTML table

I have a rather big table where I dynamically remove some rows. It works, but it is very slow. Right now it takes approx. 1.5 seconds to remove 50 rows on IE8 and Firefox (almost no difference between the browsers).
I know that DOM manipulation is slow in general, but there must be a faster way to do this.
Right now, I'm using this syntax:
$("#myTable tr").slice(250, 300).remove();
The offsets in the slice() method may vary. I use slice() since this was recommended in jQuerys help and other methods to perform the same thing - like find() or eq() - where not faster. I read about doing an empty() before the removal, but that was even slower.
Consider using the actual javascript, in case jQuery is triggering render refreshes: http://jsfiddle.net/MbXX5/
var removeRows = function(ofTable,from,to) {
for(var row=to; row>=from; --row) {
ofTable.deleteRow(row);
}
};
As you can see in the jsfiddle, this is instant. Note that I'm traversing the array in reverse, so that the row numbers remain correct. There is a chance this improves the performance, depending on the DOM code and the JIT strategies the browser uses.
[Edit: new jsfiddle with colour-coded cells to make it really obvious which rows have gone]
The problem is that for every row that you .remove(), the table is redrawn by the browser. To make it faster, remove the table from the DOM, take out the lines and put the table back at its place.
$table = $("#myTable").clone(true,true);//First true to keep events, second true to deepcopy childs too. Remove it if you do not need it to make it faster.
$table.find("tr").slice(250,300);remove();
$("#myTable").replaceWith($table);
You can use filter but I don't think it will be faster
$("#myTable tr").filter(function(index){
return index > 250 && index < 300;
).remove();
The problem is the browser tries to update the screen view of the DOM on each row removal.
You can do it by one of
removing the table, from the document, removing all rows and after
that inserting it back
cloning the table, removing elements on the clone, replacing the table with the clone
or if the amount of rows remaining is less than the ones remove, you could create a new table, insert all the rows in that and replace the existing table with the new one
The main idea is for the table to not be attached to the DOM when you do the removals, this way it will only update the view once all the rows are removed.
Is it possible you add an ID to each row? And then select the rows directly by ID and removing the rows? Like so:
var el = document.GetElementById("RowID_1");
document.removeChild(el);
jQuery is on top of Javascript. I guess using javascript directly is faster.
edit:
Ofcourse you can create a loop like this:
for(i=250;i<=300;i++)
{
var el = document.GetElementById("RowID_" + i);
document.removeChild(el);
}
edit 2:
Hide the table while editing so the browser does not update after each removal ? ;)
Try this . i hope it will help you
$("#myTable tr").slice(250, 300).html('');

Updating only one cell of a table

I created a 3x3 table. Each column is generated using a function. The function basically returns a "td" element. Else where in the code I trigger an event based on some conditions. Whenever the event is triggered, I want to update one particular cell of the table. None of the cells have ids attached to them.
My question is how can I link up the "td" that I want to be updated with the event?
I have no specific context that refers to this td alone.
If you're not using any other tools like jQuery my approach might be to find the table which I assume you can do with Javascript. Then for each td element in the table inject a class to them that is unique. You could just give them numbers or something easy. Assuming the numbering never changes you now have an easy way to lookup the td elements later in your code without having to keep a reference to the td element you want.
Instead of adding a class you could just get all the td elements in the table and if you knew the 4th element was always the cell you wanted then you could just keep a reference to that td element.
Without using jQuery or anything, you can use DOM selectors such as .childNodes (and iterating till you're satisfied), .lastChild, .firstChild, .parentNode etc.
This link gets you through some examples.
Although, if you are using this a lot, create ID dynamically in JS. Like iterating once through all your table (with .childNodes), assigning an ID (like row1-col2) to every td. It will simplify the rest of your code.
Here is a jsFiddle to show you how with jQuery:
http://jsfiddle.net/HzBFE/

Categories