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);
}
Related
I started creating some minor code within my site, and i wanted to do some dynamic creation, so some span tags are created using a javaScript for loop.
In the same code, but a different loop i want to add an Event Listener to the tags.The error i get is the element created is non existent, and i have a few ideas why it's not working, but searching the Web and Stack Overflow gave me no answers.
I've considered putting both for loops into a function and calling that function in a similar fashion jquery works with it's document ready function. But i don't think that will fix the issue
var country = ["is_AmericaN", "is_Europe",
"is_Africa","is_AmericaS","is_Asia","is_Australia"];
var spanInto = document.getElementById("spanSelect");
for(i=0; i<6; i++)
{
var spanMake = document.createElement("SPAN");
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
}
The code above creates the elements, the code below tries to call them
var countryClass = doucment.getElementsByClassName("spanLanguage");
for(i=0; i< document.countryClass.length; i++)
{
countryClass[i].addEventListener("click", function(){
var hrDisplay = document.getElementById("selectiveDisplay");
hrDisplay.removeAttribute("id");
hrDisplay.className = "noDisplay";
},false);
}
I expect the working code to, once clicked on any span tag, set the display of the hr tag to block or flex. I dont want to create 5-6 span tags manually, it has to be a dynamic creation.
You are missing the position of the adding class
var spanMake = document.createElement("SPAN");
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
Here you are assigning the class after appending it into span, that is wrong you need to assign class before.
var countryClass = doucment.getElementsByClassName("spanLanguage");
for(i=0; i< document.countryClass.length; i++)
{
doucment is document and document.countryClass should be countryClass as you already have the instance of the element
var country = ["is_AmericaN", "is_Europe",
"is_Africa", "is_AmericaS", "is_Asia", "is_Australia"
];
var spanInto = document.getElementById("spanSelect");
for (i = 0; i < 6; i++) {
var spanMake = document.createElement("SPAN");
spanMake.textContent = country[i];
spanMake.className += "spanLanguage" + " " + country[i];
spanInto.appendChild(spanMake);
}
var countryClass = document.getElementsByClassName("spanLanguage");
for (i = 0; i < countryClass.length; i++) {
countryClass[i].addEventListener("click", function() {
var hrDisplay = this;
hrDisplay.removeAttribute("id");
hrDisplay.className = "noDisplay";
}, false);
}
.noDisplay {
display: none;
}
<span id="spanSelect"></span>
<br/>
//click on any of them to replace the class
There are multiple points to be corrected:
There was a type "doucment" in your code.Use "document" instead.
Created elements didn't have any text on it, how will you call click
on element when it is not visible in DOM.
Events are attached to anchors/button not span.
Not sure what you are trying to do by attaching events.
below is the code snippet which works for you when you try to add events on dynamic created elements.Let me know if you need further help
function temp() {
var country = ["is_AmericaN", "is_Europe",
"is_Africa", "is_AmericaS", "is_Asia", "is_Australia"
];
var spanInto = document.getElementById("spanSelect");
for (i = 0; i < 6; i++) {
var spanMake = document.createElement("a");
spanMake.innerHTML = country[i];
spanInto.appendChild(spanMake);
spanMake.className += "spanLanguage" + " " + country[i];
}
}
function attachEvent() {
var countryClass = document.getElementsByClassName("spanLanguage");
for (i = 0; i < countryClass.length; i++) {
countryClass[i].addEventListener("click", function(event) {
console.log("I am called" + event.target);
//var hrDisplay = document.getElementById("selectiveDisplay");
//hrDisplay.removeAttribute("id");
//hrDisplay.className = "noDisplay";
}, false);
}
}
a {
padding: 20px;
}
<body>
<div id="spanSelect"></div>
<div id="selectiveDisplay"> </div>
<button onclick="temp()"> Call Me </button>
<button onclick="attachEvent()"> Attach Event </button>
</body>
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.
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