Create multiple HTML elements in for-loop from array - javascript

I want to create some HTML Elements of the same type with a for loop in JavaScript.
I wonder if I need to create a new Javascript variable for every element I want to show in the DOM or is it enought to override the same element again and again in my loop?
I wrote this code but it does only show one element as output:
let i;
for( i = 0; i < events.length; i++){
let tabElement = document.createElement("div");
tabElement.className = "tabElement";
tabElement.className = "ellipsis";
tabElement.id = "tabElement" + i;
tabElement.innerHTML = events[i].name;
let tabElementLink = document.createElement("a");
tabElementLink.className = "tabElementLink";
tabElementLink.id = "tabElementLink" + i;
$("tabElementLink").append(tabElement);
$(".tabBar").append(tabElementLink);
}
Than I wrote the following code but it this applies the same innerHTML to all returned elements.
let tabElements = {};
let tabElementsLink = {};
let i;
for( i = 0; i < events.length; i++){
tabElements['tabElement' + i] = document.createElement("div");
tabElements['tabElement' + i].className = "tabElement";
tabElements['tabElement' + i].className = "ellipsis";
tabElements['tabElement' + i].id = "tabElement" + i;
tabElements['tabElement' + i].innerHTML = events[i].name;
tabElementsLink['tabElementLink' + i] = document.createElement("a");
tabElementsLink['tabElementLink' + i].className = "tabElementLink";
tabElementsLink['tabElementLink' + i].id = "tabElementLink" + i;
tabElementsLink['tabElementLink' + i].append(tabElements['tabElement' + i]);
$(".tabBar").append(tabElementsLink['tabElementLink' + i]);
}
Which approach is right to generate multiple HTML elements from an array?

No metter, you can create every time new variable or rewrite. Better create variable every time.
your code can be optimized with new features and without any variables:
const events = [
{
name: "event1"
},
{
name: "event2"
},
{
name: "event3"
}
]
// if events is iterable
events.forEach((event, index)=>{
// for next lines, you forget href
$(".tabBar").append(`<div class="tabsElement ellipsis" id="tabelement${index}">${event.name}</div>`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabBar"></div>
And i don't think that you need any id at all, better to use data-id or something

Related

How to give unique ids to each child div created dynamically?

The function displays eight elements on click in dynamically created divs using the slice() method. How can I give a unique id to each div? Your suggestions would be of great help to me.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++) {
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
}
I have tried this but it's not working:
var mainDiv = document.getElementById('container');
var first = mainDiv.getElementsByTagName('div')[0];
first.id = 'one';
You can do it right inside the for loop while it's iterating:
for (i = 0; i < newArray.length; i++)
{
x += '<div id="box-' + i + '"> class="box">' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
You can use assign an ID inside the text string.
Here are a couple of other things you can do to improve this code:
Move the getElementById outside the loop
use js methods instead of string concatenation
Something like this (untested):
// get the container
container = document.getElementById('container');
for (i = 0; i < newArray.length; i++)
{
// create a div
var div = document.createElement('div');
// add attributes
div.setAttribute("id", "box-" + i);
div.setAttribute("class", "box");
// create text node
var textnode = document.createTextNode("This is div #" + i);
// add text to div
div.appendChild(textnode);
// append to container
container.appendChild(div);
}
How about giving it the id when creating? Also put the class=box in quotations like so -> class="box".
And add the whole div construct only once after the for loop. Because right now you are basically overwriting the whole thing multiple times.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
// Change class and add custom id
x += '<div class="box" id="box-'+i+'">' + newArray[i] + '</div>';
}
document.getElementById('container').innerHTML = x; // Add divs after for loop
x = "";
count += 8;
}
Now each box has a unique id going from box-0, box-1, ... to box-n

For loop through Array only shows last value

I'm trying to loop through an Array which then uses innerHTML to create a new element for every entry in the array. Somehow my code is only showing the last value from the array. I've been stuck on this for a few hours and can't seem to figure out what I'm doing wrong.
window.onload = function() {
// Read value from storage, or empty array
var names = JSON.parse(localStorage.getItem('locname') || "[]");
var i = 0;
n = (names.length);
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML = "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
}
I have a UL with the id 'list' in my HTML.
Change your for loop:
for (i = 0; i <= (n-1); i++) {
var list = names[i];
var myList = document.getElementById("list");
myList.innerHTML += "<li class='list-group-item' id='listItem'>"+ list + "</li>" + "<br />";
}
Use += instead of =. Other than that, your code looks fine.
I suggest you to first make a div by create element. there you add your innerHTML and after that you can do the appendchild. That will work perfectly for this type of scenario.
function displayCountries(countries) {
const countriesDiv = document.getElementById('countriesDiv');
countries.forEach(country => {
console.log(country.borders);
const div = document.createElement('div');
div.classList.add('countryStyle');
div.innerHTML = `
<h1> Name : ${country.name.official} </h1>
<h2> Capital : ${country.capital} </h2>
<h3> Borders : ${country.borders} </h3>
<img src="${country.flags.png}">
`;
countriesDiv.appendChild(div);
});
}

Use for loop to create mulitiple variables?

I want to use for loop to create multiple variables.
I want to create
var node0 = document.getElementById("refresh_table_0");
node0.innerHTML="";
var node1 = document.getElementById("refresh_table_1");
node1.innerHTML="";
var node2 = document.getElementById("refresh_table_2");
node2.innerHTML="";
this is my imagination code:
for(i=0;i<3;i++){
var node+i = document.getElementById("refresh_table_i");
node+i.innerHTML="";
}
First, this is javascript.
Second, the imagined code has errors, should be ("refresh_table_" + i).
Try using js arrays instead.
var node = new Array();
for(i=0;i<3;i++){
node[i] = document.getElementById("refresh_table_" + i);
node[i].innerHTML="";
}
To just initialize all the items, you can simply do this as there's no need to retain each separate DOM object:
var node;
for (var i = 0; i < 3; i++) {
node = document.getElementById("refresh_table_" + i);
node.innerHTML = "";
}
Or, even just this:
for (var i = 0; i < 3; i++) {
document.getElementById("refresh_table_" + i).innerHTML = "";
}

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Why is my Javascript not valid?

I have a div with ID 'adpictureholder', to which I dynamically add (or remove) images.
On Form submit I want to get SRC values of all these images within that DIV and put them to the value of one hidden input with ID 'piclinkslisttosubmit'. The thing is that my current Javascript does not function as if there is some syntax typo there, but I don't see where. Can anyone please have a quick look at it?
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes[].length - 1;
var images = document.getElementById('adpictureholder').childNodes[];
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
Change childNodes[] to simply childNodes.
You don't need to specify that a variable you're referencing is an array by adding brackets.
Your javascript isn't valid because you keep putting childNodes[] you can solve that by replacing childNodes[] with simply childNodes
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
} ​
You shouldn't use [] when reading a property value:
var images = document.getElementById('adpictureholder').childNodes;
You can then get the length from the array, instead of reading the property again:
var endi = images.length - 1;
First off you don't need the [] after childNodes. that causes an error.
You also were forgetting that childNodes includes text nodes and would not work properly, because they did not all contain the src property. I've corrected that in the following example:
function copyonsubmit() {
var str = '';
var textbox = document.getElementById('piclinkslisttosubmit');
var i = 0;
var images = document.getElementById('adpictureholder').childNodes;
var numImages = images.length - 1;
var src = "";
for (i = 0; i < numImages; i++) {
if (images[i].tagName === "IMG") {
str += images[i].src + '|';
}
}
str = str.slice(0, -1); // cut off the final |
textbox.value = str;
}
http://jsfiddle.net/NWArL/2/
Secondly you could write this really simply with jQuery.
var str = "";
$("#apictureholder").children("img").each(function() {
str += $(this).attr("src") + "|";
})
$("#piclinkslisttosubmit").val(str);
Third off make sure to check your console for errors. It was very clear when I ran this code on JSFiddle that it had a problem.
Finally, what exactly are you trying to do?
Change childNodes[] to childNodes and rest looks fine to me,
Read about childNodes
Try,
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
You said you were using jQuery, but you presented us with vanilla Javascript. I took the liberty of converting your code to jQuery and cleaning it up a bit. The others have already identified your problem, though.
function copyonsubmit() {
var strump1 = '';
var images = $("#adpictureholder")[0].childNodes;
for (var i = 0; i < images.length; i++) {
strump1 += '|' + images[i].src;
}
$('#piclinkslisttosubmit').val(strump1);
}​

Categories

Resources