Adham
Adham

Reputation: 1

JavaScript.. Document.write.. weird document behaviour:'(

I'm getting some very weird behaviour:( i hope someone can help

Using xmlhttp request im getting a javascript file with document. write and it looks something like this:

document.write("<input type='hidden' name='orange' value='17' />");
document.write("<input type='hidden' name='apple' value='29' />"); 

I basically want to add those input elements in a form which is inside an iframe.

// i get the document of the iframe
var docc = doc.getElementById("rs-iframe").contentDocument;
var body = docc.getElementsByTagName('body')[0];

// i put the response from xmlhttprequest in a script tag
var script = docc.createElement('script');
script.type = "text/javascript"; 
script.text = "//<![CDATA["+xmlhttp.responseText+"//]]>";

// i get the position where i want to put my script tag
var elem = form.getElementsByTagName('script')[6];  

// i try to insert my script tag from xmlhttprequest before the script i retrieve from the form
elem.parentNode.insertBefore(script, elem);

// the i append the form to the body of the iframe document                      
body.appendChild(form);

Now when i try to get doc.getElementsByTagName('input'); i only get the elements that were added from the document.write and he other form elements have disappeared :(

I appreciate all help, thanks.

Upvotes: 0

Views: 234

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117334

That's what write() is doing, it writes inside a document. If the document is already closed(closed means completely loaded), write() will overwrite the document.

Solution is simple: don't use write() when the document is already loaded. Use DOM-methods like appendChild() or insertBefore() to inject new nodes.

Upvotes: 4

Related Questions