Replacing DOM Nodes with new nodes.
I have a collection of DOM nodes I would like to replace with new DOM nodes. Due to the way I pass the information into the function I only have a variable named collection which is an object full of HtmlTableRowElements and I would like to replace it with a new variable called Rows.
Here is what I have
v开发者_开发百科ar parent = collection[0].parentNode;
parent.innerHTML = "";
parent.appendChild(rows);
however this gives me a long strange error.
uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMHTMLTableSectionElement.appendChild]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://127.0.0.1/test.php :: :: line 103" data: no]
So I have also tried
collection[0].parentNode.innerHTML = "";
collection[0].parentNode.appendChild(rows);
which returns
collection[0].parentNode is null
I do understand why the second option is returning an error. I would imagine the first option is returning an error because I have removed the element the variable is referencing.
I'm beginning to think that looking for the parent and replacing it's contents is not the way to go about this.
any help?
What is in rows
? I can't tell from your question
If it’s an array, put the contents into a document fragment and append that:
var fragment = document.createDocumentFragment(); for (var i = 0, l = rows.length; i < l, i++) { fragment.appendChild(rows[i]); } parent.appendChild(fragment);
Putting a bunch of elements in a document fragment is faster than appending them to something in the document one by one, and is a good way to carry around a collection of elements (instead of an array).
If it’s a string, use
innerHTML
:parent.innerHTML = rows;
When you call collection[0].parentNode.innerHTML = ""
, collection gets removed from the document. It still exists only because you’re holding onto it in a JavaScript variable, but no longer has a parent node. You should still be able to grab parent
in advance (like you do in the first example), and append things to it:
var parent = collection[0].parentNode;
parent.innerHTML = "";
parent.appendChild(rows);
parent.innerHTML = "";
is one way to clear the content. You then have to iterate over the other elements and append them:
for(var i = 0, l = rows.length; i < l; i++) {
parent.appendChild(row[i]);
}
But afaik it might be problematic to append new rows this way. It might be better to use table.insertRow
[MDN].
精彩评论