Reputation: 19
i have some project that need to change multiple iframe with some array example
<ul>
<li>
<iframe src="test.html">
<head></head>
<body>
<div class="content">
<p>test</p>
</div>
</body>
</iframe>
</li>
<li>
<iframe src="test.html">
<head></head>
<body>
<div class="content">
<p>test</p>
</div>
</body>
</iframe>
</li>
</ul>
I need to change <div class="content"><p>test</p></div>
for each iframe
with an array ["<h1>tittle</h1>","<h1>tittle2</h1>"]
.
For the first iframe it will be replaced with the HTML in array[0]
and second iframe with array[1]
.
Can anyone help? Thanks
Upvotes: 0
Views: 542
Reputation: 598
You could try this:
var iframe = $('iframe');
for (i=0; i<iframe.length; i++){
var current = $('iframe')[i+1].contentWindow.document.body.innerHTML;
$('iframe')[i].contents().find('html').html(current);
}
Upvotes: 0
Reputation: 90
As much as you tagged your post with "jQuery", I suppose you can use this library.
So you just need to iterate over the .each()
function.
var array = ["<h1>tittle</h1>","<h1>tittle2</h1>"];
$(".content").each(function(i) {
$(this).html(array[i]);
});
You can obviously replace html()
with replaceWith()
if you really want to delete the div
.
Upvotes: 0
Reputation: 22500
Try with replaceWith()
var array = ["<h1>tittle</h1>", "<h1>tittle2</h1>"]
$(document).ready(function() {
$('iframe').load(function() {
$('iframe').each(function(a) {
$(this).contents().find('body').children('.content').replaceWith(array[a]);
})
})
})
Upvotes: 1
Reputation: 12880
Here you go :
var arr = ["<h1>tittle</h1>","<h1>tittle2</h1>"];
var found=0;
$('iframe').each(function(){
if($(this).find('.content p').length > 0){
$(this).find('.content p').parent().replaceWith(arr[found]);
found++;
}
});
It searches for every iframe, then checks if it contains the tags you want, then replaces them with your array's replacement.
The variable 'found' allows you to travel through the array.
Upvotes: 0