Is it possible to create a div with a unique ID using a for loop?
for (var i = 0, n = 4; i < n; i++) {
var divTag = document.createElement("div");
divTag.id = "div"i;
divTag.innerHTML = Date();
document.body.appendChild(divTag);
}
Shouldn't this code produce 4 Unique DIVs containing the current date? At the moment it returns nothing.
Use
divTag.id = "div" + i;
And it will produce unique ID
Give this a shot:
divTag.id = 'div' + i;
Try
divTag.id = "div" + i;
instead of
divTag.id = "div"i;
Then it should work
Related
I'm trying to make my dynamically added divs draggable but if I call after
$("#draggable").draggable({});
this
for( var i = 0; i < 5; i++ ){
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
}
there is no chance to make divs draggable.
I know it works if i create divs first but I need to keep it like this because of my project and this example shows my problem.
Here is fiddle: http://jsfiddle.net/bimbochobot/9jstfwpm/4/
Thank you in advice.
You will have to initialize draggable widget after appending new element.
Try this fiddle:
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.backgroundColor = 'blue';
document.body.appendChild(smallone);
$(smallone).draggable({});
}
Use a class instead of id as id must be unique
$(".draggable").draggable({});
Assign draggable class to all divs
simple 1 ...
for( var i = 0; i < 5; i++ )
{
var smallone = document.createElement('div');
smallone.id = "draggable";
smallone.className = "smallDiv";
smallone.style.bacgroundColor = 'blue';
document.body.appendChild(smallone);
$(".smallDiv").draggable({});
}
it is working... http://jsfiddle.net/9jstfwpm/7/
I would like to create several divs with the same options like color, width, height, etc.
I would like to add all of these divs to an array, but I need to do this dynamically.
My current code:
var ArrayInfo = [];
do {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
}while(i < x);
x can be a very very large number.
Is this the right way to add div a to an array?
How can I write text into the elements of an array?
I tried this:
ArrayInfo[i].innerHTML = "something";
But it didn't work.
You never increment i, so your loop will never end.
Second, you never actually add any of the divs to the document -- creating them doesn't do that for you.
And as noted in the comments, you can't use the same id over and over.
var ArrayInfo = [];
var x = 10;
var ctr = document.getElementById('ctr');
for (var i = 0; i < x; ++i) {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div' + i;
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
ctr.appendChild(InfoDiv);
}
for (i = 0; i < x; ++i) {
ArrayInfo[i].innerHTML = "div " + i;
}
<div id=ctr></div>
I'd avoid using do...while. I'd also avoid creating a new div on every loop. Instantiate once, then clone (it's faster).
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
var ArrayInfo = [];
for(var i = 0; i < x; i++) {
var div = InfoDiv.cloneNode(true);
div.id += i; // Add number to id
ArrayInfo.push(div);
}
IDs must be unique! Considering adding a number to the end of each Info_Div to uniquely identify it.
Also consider using a for loop instead of a do while loop.
The convention for JavaScript variables is lowerCamelCase. So we should fix that as well.
In your code, the divs were added to the array but not to the document. If you wanted to add them to the DOM, you would have to add document.body.appendChild.
Your code would look more like this.
var arrayInfo = [];
var x = 5; // Or whatever value it is
for (var i = 1; i < x; i++) {
var infoDiv = document.createElement('div');
infoDiv.id = 'Info_Div' + i;
infoDiv.className = 'Info_Div';
infoDiv.style.width = "100px";
infoDiv.style.height = "30px";
infoDiv.style.display = "inline-block";
arrayInfo.push(infoDiv);
arrayInfo[i].innerHTML = "div " + i;
document.body.appendChild(infoDiv);
}
JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.
There is some part of my code that gives me headaches. I've missed something. I want to create, declare variables by array but it won't work. It works fine when I declare them manually (like am1=1; am2=2;...). But the problem is when I try the for loop and to create variables that way.
There is the FIDDLE of my problem
myhtml.html
1.Question:<br/>
<textarea name="question11" ></textarea><br/><div id="inner1"></div><button type="button" onClick="addmore1();">Add more</button>
<br/><br/>
2.Question:<br/>
<textarea name="question21" ></textarea><br/><div id="inner2"></div><button type="button" onClick="addmore2();">Add more</button>
myscript.js
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am1++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am1;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am2++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am2;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
Here is the fiddle with the fix for your problem.
If you look at the developer console (F12 in most browsers), you can see the error: am1 and am2 are undefined.
I guess what you meant to do is to refer to am[1] instead of am1. Althought the code is working after that change, there is a lot of room for improvement: you could reuse more code by having only one addmore function, etc . e.g.:
function addmore(index) {
am[index]++;
var textarea = document.createElement("textarea");
textarea.name = "question" + index + am[index];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
if you are declaring them by array, why aren't you using them by array?
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am[1]++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[1];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am[2]++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[2];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
or am I missing something?
You must use .push() to add values to an array.
var am = [];
for(i=1; i<3; i++){
am.push(1);
}
Sorry if I didn't answer your question completely.
for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}