Reputation: 1643
Is it possible to query the length of an array and then use JS/jQuery to create the same amount of new HTML elements client side?
The code I have for the array is:
var psC1 = [
'item1',
'item2',
'item3'
];
alert(psC1.length);
Which will alert that there's 3 items in the array. I now want to create three iframes on the page, and index the array into the src attribute of each element.
The code I'd use to insert the src of the iframes using the array would be:
$('.test-iframe').each(function() {
$(this).attr('src', psC1[$(this).index()]);
});
What I'm struggling with is after counting the array, is creating three iframes with JS/jQuery.
Upvotes: 0
Views: 143
Reputation: 14881
You can make this cleaner with jQuery.map
:
$('body').append($(psC1).map(function (i, src) {
return $('<iframe>').attr('src', src);
}).get());
Upvotes: 0
Reputation: 3105
You could use a loop to create the HTML
var iframeHTML = "";
for (int i = 0; i < count; i++)
{
iframeHTML += "<iframe class='test-iframe'></iframe>";
}
then append the HTMLString where you want.
Upvotes: 0
Reputation: 191789
for (var x = 0; x < psC1.length; x++) {
$("<iframe>", {'src': x}).appendTo("body");
}
The $("<iframe>")
syntax creates the element. .appendTo
adds it to the DOM. Note that this will just create iframes with source of "0," "1," and "2," so you probably want something like '/some/path/?page=' + x
as the src
.
Note that you could also use $.each
instead of a normal for
loop, but it's more expensive and, in my opinion, unnecessary.
Upvotes: 1
Reputation: 1075139
To create an iframe
with jQuery, you use the $
function (or jQuery
in no-conflict mode):
$("<iframe>").appendTo(document.body);
Of course, you don't have to append to body, you can put the iframe wherever you need it.
In your case, perhaps something like this:
$.each(psC1, function(index, value) {
$("<iframe>").attr("src", value).appendTo(document.body);
});
$.each
loops through the array entries.
Upvotes: 2