Categories
Iframe Jquery

Insert HTML content into an iFrame using jQuery

To Insert HTML content into an iFrame we can use jQuery contents() method. The jQuery contents() method will return all the direct childrens incliding text and comment nodes of the selected element.

In the below example first we are finding the iFrame in the body section and then we are getting the value to be inserted into the iFrame. Finally we are placing the value in the iFrame.

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
<style type="text/css"> 
*{
   margin: 10px;
}
textarea,iframe { 
   display: block; 
} 			
iframe { 
   width: 100%;
   border: 1px solid #000000; 
} 
</style> 
</head> 
<body> 
<h1>Insert HTML content into an iFrame using jQuery</h1> 
<textarea>This ia a sample text to insert in iFrame.</textarea> 
<button type="button" onclick="updateIframe()">Click here to Insert content</button> 
<iframe style="text-align:center;" id="iframe"></iframe> 
<script type="text/javascript"> 
function insertIframe() { 
var iFrame = $("#iframe").contents().find('body'); 
var textValue = $("textarea").val(); 				iFrame.html(textValue); 
} 
</script> 
</body> 
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *