lc******@gmail.com wrote:
Hi all,
Does anyone know if there is an easy way to create the html
representation of an HTMLElement object in javascript?
innerHTML is a property invented by MS and widely copied. There is no
public specification, so others have simply copied MS's implementation
with varying degrees of exactitude.
It generally works OK except that not all DOM attributes are represented
in HTML, for example you can't differentiate between current value and
default value for a text input, you can only set the value attribute:
<input ... value="foo">
which now becomes the default value and the current value. In Firefox,
the innerHTML value attribute remains as per the original source HTML,
but in IE it becomes whatever the current value is. So in Firefox you
lose the current value, in IE you lose the default value.
I'm attempting
to update the innerHTML property of a div element to allow user entries
to presist when the the input display pane is changed. Basically I have
several different div panes that users can rotate through when entering
values of a simulated form whose values are then parsed and used to
dynamically display content using ajax style methods. The innerHTML
property seems to update in IE as users input values and this works
fine. However, with firefox a user's values are lost when I update the
innerHTML property of one of the hidden div elements. So basically I'm
trying to write a method that will build the updated html with
checkboxes checked etc so that I can use the generated html as the
value of the innerHTML property of the div I'm trying to update.
Have you considered hiding the forms using the display attribute? Or
removing them from the document and storing them in an object? Then you
can replace them whenever you want. Serialising elements using
innerHTML then writing them back out again does not seem to be a good idea.
Try this sample that removes the object by storing it in a global
object, then restores it. When archived, the form is kept as-is. It is
still available to script if you want to do anything with it but it's no
longer part of the document.
<script type="text/javascript">
var elStore = {};
function archiveEl(id) {
var el = document.getElementById(id);
elStore[id] = el.parentNode.removeChild(el);
}
function replaceEl(childID, parentID) {
if (childID in elStore) {
var p = document.getElementById(parentID);
p.appendChild(elStore[childID]);
}
}
</script>
<button onclick="archiveEl('formA');">Remove formA</button>
<button onclick="replaceEl('formA','frameA');">Restore formA</button>
<div id="frameA">
<form id="formA" name="formA" action=""><div>
<input type="text" name="t0" value="t0 default"><br>
<input type="text" name="t2" value="t0 default"><br>
<input type="radio" name="rset0" value="rs0" checked><br>
<input type="radio" name="rset0" value="rs1"><br>
<input type="radio" name="rset0" value="rs2"><br>
<input type="submit"><input type="reset">
</div></form>
</div>
--
Rob