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.
Related
I am looking to script a site that has a set of changing values. I am trying to figure out how to call the text value inside of only one of these entries at a time.
Any one of these can look like this
<tr ng-repeat="(key, game) in crash.games.slice().reverse()" class="" style="">
<td ng-if="::game.crash > 199" class="crashHighResult">RANDOM NUMBER THAT I WANT TO SEE</td>
tr is the parent of td and the text value inside of td is what I'm trying to see
The only problem I'm experiencing is that there are as many as 20 entries stored during this time and they can all have seemingly the same classes and parents as every other one, the only difference being the random number value...
I am thinking that If I can pull them all at the same time and then maybe create an array with those values I might be able to do what I need to do but I'm a bit stumped.
I am very new to javascript and jquery and this is a learning experience for me. Thanks for your help!
Your best bet would be to use document.querySelectorAll if you want to understand some native JS techniques. There are a couple of other ways of getting the elements you want (getElementsByClassName and getElementsByTagName) but they don't play nearly as well with forEach as does the former.
So, to grab the elements:
let cells = document.querySelectorAll('td');
And to loop over that nodelist:
cells.forEach(function (cell) {
console.log(cell.textContent);
});
At the moment the code just logs the text content (your random number) to the console, but you can get a feel for what you can now do with that data.
For example, to get the last (most recent?) random number (the last cell in the nodelist) you would use:
let rnd = cells[cells.length - 1].textContent;
Hope this helps you out.
If you need to select the first tr td in the table to get the value, using jQuery you can select all tr td elements and then specify the first one.
$("tr td").first().text();
This selector finds all tr td elements as it traverses the dom, so it will find the top row in the table first. The first() function returns a jquery object of the first element found. The text() gets whatever text is inside the td tags, basically the same as the js innertext or textcontent.
If you want to do processing with all the values you can use the jquery selector each() function.
$("tr td").each(function (index , element) {console.log($(element).text())})
This loops through all the elements and prints their values to the console, but you could modify the function to sum the values, put them in an array, or whatever.
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);
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('');
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.
I was wondering if there was a way of adding JavaScript in every occurrence of a certain HTML tag, e.g.
<td onmousedown="">
At the moment I just have it in every single one of my td tags in my table, but there must be a cleaner way. Something like adding JavaScript in the way CSS adds formatting.
What your looking for is most likely "event binding." This can be done via your script rather than embedded in the HTML code. There are lots of different ways to accomplish such a task, here is one of them using "td" as in your example.
var items = document.getElementsByTagName("td");
for (var i=0; i<items.length; i++) {
items[i].onmousedown = YourMouseDownFunction;
}
You want jQuery. See http://jQuery.org This can be accomplished using a "selector" (jquery term)
Add an event listener (See also: Quirks Mode on events and on event listeners) to your document looking for mousedown events and filter it on the basis of the originating element.
There is a good answer here on Stackoverflow as well.