Adding IFRAME to DOM with Javascript

I want to add an iframe to the page. This iframe must link to a URL. I have added the code below to the HTML page, but it does not work:

 document.createElement('<iframe src='http://example.com'></iframe>'); 
+6
source share
3 answers

Here you go:

 var iframe; iframe = document.createElement('iframe'); iframe.src = 'http://example.com/file.zip'; iframe.style.display = 'none'; document.body.appendChild(iframe); 

Live demo: http://jsfiddle.net/USSXF/2/

Your code does not work because you pass the entire HTML string to the createElement function ("jQuery style" :) ), which is not valid. A valid parameter for this function is a string representing the tag name (for example, 'div' , 'iframe' , 'p' , etc.).

Read about document.createElement here.

+13
source

You need to add node to the DOM using document.appendChild

You also need to avoid your inner quotes or use double quotes.

+1
source
 document.write(unescape('%3Ciframe src="//example.com/file.zip"%3E%3C/iframe%3E') 
-1
source

Source: https://habr.com/ru/post/890315/


All Articles