Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I set the content of an iframe without src using jQuery?
To set the content of an iframe without src, use the jQuery html() method. This technique allows you to dynamically populate an iframe with custom HTML content by accessing its document context through jQuery.
Method Overview
When an iframe has no src attribute, you can inject content directly into its document. The key is to access the iframe's contentWindow.document and then use jQuery to manipulate its content.
Example
You can try to run the following code to learn how to set the content of an iframe without src attribute −
<!DOCTYPE html>
<html>
<head>
<title>jQuery Iframe Content</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Access the iframe's document context
var context = $('iframe')[0].contentWindow.document;
// Get the body element within the iframe
var $body = $('body', context);
// Set the HTML content
$body.html('<h2>Hello World!</h2><p>This content was added using jQuery.</p>');
// Optional: Add some styling
$body.css({
'font-family': 'Arial, sans-serif',
'padding': '20px',
'background-color': '#f0f8ff'
});
});
</script>
</head>
<body>
<h3>Parent Page Content</h3>
<p>The iframe below will be populated with content using jQuery:</p>
<iframe style="border: 2px dotted #333; width: 400px; height: 200px;"></iframe>
</body>
</html>
How It Works
The code works in three main steps:
1. Access the iframe's document: $('iframe')[0].contentWindow.document gets the document object of the first iframe on the page.
2. Target the body element: $('body', context) selects the body element within the iframe's document context.
3. Set the content: The html() method injects the desired HTML content into the iframe's body.
This method provides a clean way to dynamically populate iframes with custom content using jQuery, making it useful for creating embedded widgets or dynamic content areas.
