Reputation: 926
Is there any way to generate any html element on run time?
Let's say, I have a text field for user to enter any number.
Requirements:
1. If user enters 10, then it should generate 10 IMG element tags.
2. We can also manipulate the value of IMG src
3. Each 10 output should be something like img src="path chosen" etc, <--Dynamically generated
Any idea/suggestions?
Upvotes: 1
Views: 1757
Reputation: 3394
HTML
<input type="text" id="myInput" />
<input type="text" id="myPath" />
Javascript
var count=document.getElementById('myInput').value;
var path=document.getElementById('myPath').value;
for(i=0; i<count; i++)
{
var img=document.createElement('img');
img.setAttribute('src', path);
parent.appendChild(img); //now append the element to the desired div
}
Upvotes: 1
Reputation: 22759
You can use document.createElement()
ie
for(var x = 0; x < 10; x++){
var img = document.createElement("img");
// set the properties
...
}
Upvotes: 0
Reputation: 2959
With a javascript framework this is easy.
jquery for example:
for(var a=0;a<number;a++){
var newelement = $('<img............../>');
$('#parentElement').append(newelement);
}
Upvotes: 0
Reputation: 15375
Example with jQuery:
HTML:
<input type="text" id="my-input" value="0" />
<div id="container"></div>
JS:
$('#my-input').change(function() {
var el = $(this);
for (var i=0; i < parseInt(el.val(), 10); i++) {
$('#container').append('<img src="blabla" />');
}
});
Upvotes: 2