im having a firefox issue where i dont see the wood for the trees
using ajax i get html source from a php script
this html code contains a tag and within the tbody some more tr/td's
now i want to append this tbody plaincode to an existing table. but there is one more condition: the table is part of a form and thus contains checkboxe's and drop down's. if i would use table.innerHTML += content; firefox reloads the table and reset's all elements within it which isnt very userfriendly as id like to have
what i have is this
// content equals transport.responseText from ajax request
function appendToTable(content){
var wrapper = document.createElement('table');
wrapper.innerHTML = content;
wrapper.setAttribute('id', 'wrappid');
wrapper.style.display = 'none';
document.body.appendChild(wrapper);
// get the parsed element - well it should be
wrapper = document.getElementById('wrappid');
// the destination table
table = document.getElementById('tableid');
// firebug prints a table element - seems right
console.log(wrapper);
// firebug prints the content ive inserted - seems right
console.log(wrapper.innerHTML);
var i = 0;
// childNodes is iterated 2 times, both are textnode's
// the second one seems to be a simple '\n'
for(i=0;i<wrapper.childNodes.length;i++){
// firebug prints 'undefined' - wth!??
console.log(wrapper.childNodes[i].innerHTML);
// firebug prints a textnode element - <TextNode textContent=" ">
console.log(wrapper.childNodes[i]);
table.appendChild(wrapper.childNodes[i]);
}
// WEIRD: firebug has no problems showing the 'wrappid' table and its contents in the html view - which seems there are the elements i want and not textelements
}
either this is so trivial that i dont see the problem OR
its a corner case and i hope someone here has that much of expirience to give an advice on this - anyone can imagine why i get textnodes and not the finally parsed dom elements i expect?
btw: btw i cant give a full example cause i cant write a smaller non working piece of code
its one of those bugs that occure in the wild and not in my testset
thx all
You are probably running into a Firefox quirk of following the W3C spec. In the spec the whitespace between tags are "text" nodes instead of elements. These TextNodes are returned in childNodes. This other answer describes a workaround. Also Using something like JQuery makes this much easier.
I would expect this behavior in any browser as the += operand overwrites what is already in the table by definition. Two solutions:
Instead of receiving HTML code from your PHP file, have the PHP generate a list of items to add to the table. Comma/tab separated, whatever. Then use Table.addRow(), Row.addCell() and cell.innerHTML to add the items to the table. This is the way I would suggest doing it, no point in creating GUI elements in two separate files.
The other solution is to save all the form data that's already been entered to local JavaScript variables, append the table, and then reload the data into the form fields.
Well, returning a JSON object with the new data seems like the best option. Then, you can synthesize the extra table elements by using it.
In case one is forced to get plain HTML as response, it is possible to use var foo = document.createElement('div');, for example, and then do foo.innerHTML = responseText;. This creates an element that is not appended to anything, yet hosts the parsed HTML response.
Then, you can drill down the foo element, get the elements that you need and append them to the table in a DOM-friendly fashion.
Edit:
Well, I think I see your point now.
wrapper is a table element itself. The nodes reside under the tbody, a child of wrapper which is its lastChild (or you can access it via its tBodies[0] member, in Firefox).
Then, using the tBody element, I think that you would be able to get what you want.
BTW, You do not need to append the wrapper to the document before appending its children to the table, so no need to hide it etc.
Related
I'm developing a little tool for live editing using Chrome DevTools, and I have a little button "Save" which grabs the HTML and sends it to server to update the static file (.html) using Ajax. Very simple indeed.
My problem is that I need to filter the HTML code before sending it to the server, I need to remove some nodes and I'm trying to achive this using jQuery, something like this:
// I grab all the HTML code
var html = $('<div>').append($('html').clone()).html();
// Now I need to remove some nodes using jQuery
$(html).find('#some-node').remove();
// Send the filtered HTML to server
$.post('url/to/server/blahblahblah');
I already tried this Using jQuery to search a string of HTML with no success. I can't achieve to use jQuery on my cloned HTML code.
Any idea about how to do this?
The DOM is not a string of HTML. With jQuery, you do DOM manipulation, not string manipulation.
What you're doing is
cloning the document (unnecessary because you convert it to HTML anyway),
appending that cloned document to a new div for some reason
converting the content of that div to an HTML string
converting that HTML back to DOM nodes $(html) (so we're back to the first point above)
finding and removing an element in those nodes
presumably posting the html variable to the server.
Unfortunately, the html string has not changed because you manipulated DOM nodes, not the string.
Hopefully you can see above that you're doing all sorts of conversions that have little to do with what you ultimately want.
I don't know wny you'd need to do this, but all you need is to do a .clone(), then the .find().remove(), then .html()
var result = $("html").clone(false);
result.find("#some-node").remove();
var html = result.html();
Maybe like this?
var html = $('html').clone();
html.find('#some-node').remove();
I have a doubt with javascript document.write method. Mostly when I use document.write() it shows me the content written with the method in a different page. For instance, if I write the command like this, document.write("Hello, My name is Sameeksha"); then the execution of this line takes me to a different document on the same page. I want to be able to append the message on the same page, with other elements of the page. For example, if I have text boxes and buttons on the page and I want the text with document.write to appear under all the content of the page or on a particular section of a page. Please suggest what can be done to get the output in this way? As, this way it will be really easy to create dynamic HTML content.
Thank you so much for your time.
Regards,
Sameeksha Kumari
document.write is basically never used in modern Javascript.
Whan you do instead is to create explicit DOM elements and append them to the document in the place you want. For example
var x = document.createElement("div"); // Creates a new <div> node
x.textContent = "Hello, world"; // Sets the text content
document.body.appendChild(x); // Adds to the document
Instead of appending to the end you can also add child nodes to any existing node. For example:
function addChatMessage(msg) {
var chat = document.getElementById("chat"); // finds the container
var x = document.createElement("div");
x.textContent = msg;
chat.appendChild(x);
}
I'd say 6502 posted the more correct way to do it, but I think someone should mention innerHTML as well. First, give some element in your HTML body an id so you can reference it:
<div id="outputDiv">I'm empty.</div>
Then, either at the bottom of your document (at the end of the <body> tag), or any other time after the page is loaded, you can update the contents with innerHTML:
document.getElementById("outputDiv").innerHTML = "<h1>Hello!!!</h1>";
Here's a jsfiddle demonstrating this. This isn't as clean/correct/elegant as using the more standard DOM methods, but it's well supported. Sometimes quick and dirty is what you need!
I'm running this code:
$('#storeTable').empty();
$('#storeTable').append("<tr>");
$('#storeTable').append("<td>");
$('#storeTable').append(returnData["1"]["ID"]);
$('#storeTable').append("</td>");
$('#storeTable').append("</tr>");
However if I run it multiple times in one page load, the 'storeTable' element gets taller and taller with every run. Am I missing something obvious, is this a gotcha of jQuery/JavaScript, is it the fault of my browser (Chrome), or am I doing something wrong?
The code obviously needs refining, I'm just trying to get a bare-bones implementation of a dynamic section of a page.
If you'd like any other details, please ask, rather than just downvoting without a comment.
storeTable is, of course, a table, too.
You can't use .append() to append partial pieces of HTML. .append() only appends whole formed objects and when it appends them it appends them as the last child of the target object.
To add to that, some browsers are picking about how you can or cannot create/remove content in tables.
Assuming #storeTable is the <table> tag, you could assign .html() to create a whole new table all at once:
$("#storeTable").html("<tr><td>" + returnData["1"]["ID"] + "</td></tr>");
Working demo: http://jsfiddle.net/jfriend00/5BVdX/
$('#storeTable').empty();
// Will create three rows, one after another
$('#storeTable').append("<tr><td>123</td></tr>");
$('#storeTable').append("<tr><td>456</td></tr>");
$('#storeTable').append("<tr><td>789</td></tr>");
// Will create three rows, each next replaces previous
$('#storeTable').html("<tr><td>123</td></tr>");
$('#storeTable').html("<tr><td>456</td></tr>");
$('#storeTable').html("<tr><td>789</td></tr>");
I am creating a large table dynamically using Javascript.
I have realised the time taken to add a new row grows exponentially as the number of rows increase.
I suspect the Page is getting refreshed in each loop per row (I am also adding input elements of type text on each cell)
Is there a way to stop the page "refreshing" until I am done with the whole table?
Any suggestion on how to do this or go around it?
I have tried all the suggestions above, but I am still getting the performance bottlenecks.
I tried to analyse line after line, and I have noted that document.getElementById() is one of the lines taking a lot of time to execute when the table is very large.
I am using getElementById() to dynamically access an HTML input of type text loaded on each cell of the table.
Any ideas on which DOM method I should use instead of getElementById()?
You can create the table object without adding it to the document tree, add all the rows and then append the table object to the document tree.
var theTable = document.createElement("table");
// ...
// add all the rows to theTable
// ...
document.body.appendChild(theTable);
Maybe build your table as a big string of HTML, and then set the .innerHTML of a container div to that string when you've finished?
Did you try the <tbody> tag when you create the table?
It is possible browsers optimize that and don't "refresh" the table while populating it.
If your cells sizes are the same for each row then you will be able to specify style table-layout:fixed - this will give you the greatest performance gain as the browser won't have to recalculate cells sizes each time a row is added
Use the table DOM to loop trough the rows and cells to populate them, instead of using document.getElementByID() to get each individual cell.
E.g.
thisTable = document.getElementByID('mytable');//get the table
oneRow = thisTable.rows[0].cells; //for instance the first row
for (var colCount = 0; colCount <totalCols; colCount ++)
{
oneCell =oneRow[colCount];
oneCell.childNodes[0].value = 'test';//if your cell contains an input element
oneCell.innerHTML = 'test'; // simply write on the cell directly
}
Hope that helps someone else...
Cheers.
What is the best plain javascript way of inserting X rows into a table in IE.
The table html looks like this:
<table><tbody id='tb'><tr><td>1</td><td>2</td></tr></tbody></table>
What I need to do, is drop the old body, and insert a new one with 1000 rows. I have my 1000 rows as a javascript string variable.
The problem is that table in IE has no innerHTML function. I've seen lots of hacks to do it, but I want to see your best one.
Note: using jquery or any other framework does not count.
Here's a great article by the guy who implemented IE's innerHTML= on how he got IE to do tbody.innerHTML="<tr>...":
At first, I thought that IE was not
capable of performing the redraw for
modified tables with innerHTML, but
then I remembered that I was
responsible for this limitation!
Incidentally the trick he uses is basically how all the frameworks do it for table/tbody elements.
Edit: #mkoryak, your comment tells me you have zero imagination and don't deserve an answer. But I'll humor you anyway. Your points:
> he is not inserting what i need
Wha? He is inserting rows (that he has as an html string) into a table element.
> he also uses an extra hidden element
The point of that element was to illustrate that all IE needs is a "context". You could use an element created on the fly instead (document.createElement('div')).
> and also the article is old
I'm never helping you again ;)
But seriously, if you want to see how others have implemented it, take a look at the jQuery source for jQuery.clean(), or Prototype's Element._insertionTranslations.
Do as jQuery does it, eg. add <table> and </table> around it, insert into document and move the nodes you want to where you want them and ditch the temp-element.
the code ended up being this:
if($.support.scriptEval){
//browser needs to support evaluating scripts as they are inserted into document
var temp = document.createElement('div');
temp.innerHTML = "<table><tbody id='"+bodyId +"'>"+html;
var tb = $body[0];
tb.parentNode.replaceChild(temp.firstChild.firstChild, tb);
temp = null;
$body= $("#" + bodyId);
} else {
//this way manually evaluates each inserted script
$body.html(html);
}
Things that beed to exist beforehand: a table that has a body with id of 'bodyId'. $body is a global variable (or the function has a closure on it), and there is a bit of jquery in there too, because IE does not evalute scripts that are inserted into the html on the fly.
I had the same problem (as do lots of other people) and after a lot of playing around here's what I got to work.
You have to make a tr via document.createelement ('tr') then make a td, the same way.
appendchild the td to the tr, appendchild the tr to tbody (not table) THEN you can innerhtml the td you created and it will work.
This was ie8 I was using. Basically the table structure has to be made with createelement but the rest of it can be innerHTMLed. I was doing this watching in the IE8 debugger and it would say it would add it (if I did tr.innerhtml="blah") and give no error, but it wouldn't display, and the html dom view showed a very broken table (no td ever showed up, but the /td did)
So when finally I did the tr AND td by createelement calls, it created a correct looking dom and drew the page correctly.