This question already has answers here:
Append multiple items in JavaScript
(15 answers)
Closed 4 years ago.
This is my code:
var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
var newDiv=document.createElement("div"); //create a new div
var newDiv2=document.createElement("div") //create a new div
newDiv.innerHTML=array[index];
newDiv.draggable = true;
newDiv.id = 'record-2-'+index;
newDiv.className = 'record';
newDiv2.className = 'record';
newDiv2.id = 'record-4-'+index;
newDiv2.draggable = true;
newDiv2.innerHTML=array[index];
div4.appendChild(newDiv); // append to div
div2.appendChild(newDiv2); // append to div
newDiv.addEventListener("dragstart", handleDragStart);
newDiv2.addEventListener("dragstart", handleDragStart);
}
How I can achive same functionality without having two separate variable newDiv, newDiv2.
You could clone the div and add that by using cloneNode(), so you are adding two separate divs, not the one same one.
var div4=document.getElementById('div4'); // get the div element
var div2=document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
var newDiv=document.createElement("div"); //create a new div
newDiv.innerHTML=array[index];
newDiv.draggable = true;
newDiv.id = 'record-2-'+index;
newDiv.className = 'record';
div4.appendChild(newDiv); // append to div
newDiv = newDiv.cloneNode(false); // clone the div
newDiv.id = 'record-4-'+index; // change its id property
div2.appendChild(newDiv); // append to div
newDiv.addEventListener("dragstart", handleDragStart);
newDiv2.addEventListener("dragstart", handleDragStart);
}
You could create a function wich return or adds the div to a passed div:
//Required..
function handleDragStart(){};
//Created and append divs
function addDivTo(div, html, id){
//appendChild() returns the input
var newDiv = div.appendChild(document.createElement("div")); //create a new div
newDiv.id = id;
newDiv.innerHTML = html;
newDiv.draggable = true;
newDiv.className = 'record';
newDiv.addEventListener("dragstart", handleDragStart)
}
//Some array used below
var array = ['123', '456', '789', 'cucubau'];
var div4 = document.getElementById('div4'); // get the div element
var div2 = document.getElementById('div2'); // create a new div
for (var index = 0; index < array.length; index++) {
addDivTo(div4, array[index], 'record4-' + index);
addDivTo(div2, array[index], 'record2-' + index)
}
<div id = 'div4'></div>
<div id = 'div2'></div>
Related
This code is not creating a single div in the webpage which i linked the js below. how can i makes changes in the js or html for the code to be executed as expected
var div,
container = document.getElementById("container");
for (var i = 0; i < 5; i++) {
div = document.createElement("div");
div.onclick = function () {
alert("This is box #" + i);
};
container.appendChild(div);
}
1) To show a div you have to include some text inside divtag
2) You should use let instead of var to get the correct number when user click on div
var div,
container = document.getElementById("container");
for (let i = 0; i < 5; i++) { // change -> let instead of var
div = document.createElement("div");
div.textContent = `div${i}` // change -> add some text
div.onclick = function() {
alert("This is box #" + i);
};
container.appendChild(div);
}
<div id="container"></div>
I'm trying to make a container div for each image and its description at each iteration in my for loop, but JQuery is lumping all the image divs and description divs together into one container div, and that's messing up the whole layout.
I'm not sure why it's doing that, especially since I'm creating a new container div and appending to it within the for loop.
Here's the JSFiddle: https://jsfiddle.net/ZEZEME/wza7q3tn/4/
HTML
<div class=PgTwo></div>
JS
$.getJSON(url, function(data) {
arr = data.data;
for (var i = 0; i < arr.length; i++) {
var articleInfo = arr[i];
console.log(articleInfo);
var imgURL = articleInfo["listingimage"]['url'];
var title = articleInfo["title"];
var desc = articleInfo["listingdescription"];
if (imgURL != "") {
var imgWrapperDiv = document.createElement('div');
var imgDiv = document.createElement('div');
var descDiv = document.createElement('div');
imgDiv.id = 'imgDiv';
imgWrapperDiv.id = 'imgWrapperDiv';
descDiv.id = 'descDiv';
descDiv.textContent = desc;
var imgurlCSS = 'url("'+imgURL+'")';
$(imgDiv).css({'background-image': imgurlCSS, 'background-repeat': 'no-repeat', 'background-size': 'cover'});
$(imgDiv).append($('<a href="" id=link >'+ title +'</a>').css('text-decoration', 'none'));
$('#imgWrapperDiv').append(imgDiv);
$('#imgWrapperDiv').append(descDiv);
$('.PgTwo').append(imgWrapperDiv);
}
}
});
You're only using one id in the for loop. So you're creating the wrapper div, then setting its id but every time it sets it to the same id as before. In the DOM only one wrapper div is present then.
I wan't add element after every DIV tag, while 'i=0','i=1','i=2'...untill 'max-DIV.length'. What should I do? I'm just a little worry.. OH!
var NewSpan = document.createElement("span");
NewSpan.setAttribute("id", "gotop");
var NewSpanText = document.createTextNode("to be continue...");
NewSpan.appendChild(NewSpanText);
var i = 0;
var OldDiv = document.getElementsByTagName('div')[i];
var parent = OldDiv.parentNode;
if (parent.lastChild == OldDiv) {
parent.appendChild(NewSpan);
} else {
parent.insertBefore(NewSpan, OldDiv.nextSibling);
};
<div id="n1">DIV</div>
<div id="n2">DIV</div>
<div id="n3">DIV</div>
<div id="n4">DIV</div>
lile this
You need to wrap this in a for loop and create a new span element every time you want to insert one.
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
var NewSpan = document.createElement("span");
NewSpan.setAttribute("id", "gotop" + i); // Can't have duplicate IDs
var NewSpanText = document.createTextNode("to be continue...");
NewSpan.appendChild(NewSpanText);
var OldDiv = divs[i];
var parent = OldDiv.parentNode;
if (parent.lastChild == OldDiv) {
parent.appendChild(NewSpan);
} else {
parent.insertBefore(NewSpan, OldDiv.nextSibling);
}
}
<div id="n1">DIV</div>
<div id="n2">DIV</div>
<div id="n3">DIV</div>
<div id="n4">DIV</div>
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.
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