How to add diferent text for each element in DOM - javascript

Can someone tell me what is wrong with this code. I want to add a number from 0 to 4, but it added only the last number from my loop.
Thank you very much in advance.
<script>
for (i = 0; i < 5; i++) {
var createEl = i;
var createEl = document.createElement("li");
for (j = 0; j < 5; j++) {
createEl.innerHTML = [j];
}
console.log(createEl);
//<li>4</li>
//<li>4</li>
//<li>4</li>
//<li>4</li>
//<li>4</li>
}

You dont need the nested for loop just use the i value from the first loop
for (i = 0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
console.log(createEl);
}
This will only print the tags to console. In case you want to put them in another tag use it like this:
var node = document.createElement("div");
for (i = 0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
node.appendChild(createEl);
}

You don't need two loops for that.
var ulContainer = document.createElement("ul");
for (i=0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
ulContainer.appendChild(createEl);
}

Related

Looping the creation of multiple variables

I want to loop the creation of various variables as to cut down on lines of code. If I need to create 10 variables like so:
var par01 = document.createElement("p");
var par02 = document.createElement("p");
var par03 = document.createElement("p");
var par04 = document.createElement("p");
var par05 = document.createElement("p");
var par06 = document.createElement("p");
var par07 = document.createElement("p");
var par08 = document.createElement("p");
var par09 = document.createElement("p");
var par10 = document.createElement("p");
...using a basic For Loop. I seem to be having some issues in setting it up:
for (var loopCounter = 1; loopCounter < 11; loopCounter++) {
var par[loopCounter] = document.createElement("p"); }
Create an array before the loop, then fill it with new entries inside the loop. You want dynamic declaration otherwise, that is a classical problem afaik.
var arr = [];
for (var i = 0; i < 11; i++) {
arr.push( document.createElement("p") );
}
You're almost there, just declare your array before the loop. You can either assign to each array item using the counter like you did, or probably easier to just use push():
var par = [];
for (var loopCounter = 1; loopCounter < 11; loopCounter++) {
par.push(document.createElement("p"));
}
console.log(par.length);
You better use an array instead of doing this kind of stuff.
var pCollection =Array();
for (var loopCounter = 1; loopCounter < 11; loopCounter++) {
pCollection.push(document.createElement("p"));
}
Now to access your elements just iterate over the array;
for (var loopCounter = 1; loopCounter < pCollection.length; loopCounter++) {
var pElement = pCollection[loopCounter] ;
}
You must define the array before, better (in performance terms) if you know the length previously.
var loopCounter,
par[] = new Array(11);
for (loopCounter = 0; loopCounter < array.length; loopCounter++) {
par[loopCounter] = document.createElement("p");
}
If the length is dynamic, you can initialize empty, and add elements using push() function.
Use an array and push each object into it:
var pCollection = [];
for (var loopCounter = 0; loopCounter < 10; loopCounter++) {
pCollection.push(document.createElement("p"));
}
console.log(pCollection);

How to create buttons and make them change color, javascript

I don't understand what the problem is. Do I have to give them unique names? If so how can I do that?
var co = document.querySelector("div");
var buttons = [];
for (i = 0; i < 10; i++) {
button = document.createElement("button");
buttons.push("button");
co.appendChild(button);
}
for (i = 0; i < 9; i++) {
buttons[i].style.backgroundColor = "blue";
}
You may push the button variable, not the string.
buttons.push(button);
For iterating the buttons, you may take the length property for iterating all buttons.
for (i = 0; i < button.length; i++) {
Don't forget to declare the index variable i at top.
var i;
Fully example of what you want :)
var co = document.querySelector("div");
var colors = ["blue","red","green","orange","black","violet","blueviolet"]
var buttons = [];
for (i = 0; i < 10; i++) {
button = document.createElement("button");
buttons.push(button);
co.appendChild(button);
}
for (i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
<div></div>

For loop through array.length only executes once

The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
var current = numbers[i];
var currentStr = current.toString();
var reverseStr = currentStr.split('').reverse().join('');
var reverseArr = [];
for (i = 0; i < reverseStr.length; i++) {
reverseArr.push(reverseStr[i]);
}
var A = 0;
for (i = 0; i < reverseArr.length; i += 2) {
A += Math.round((reverseArr[i]));
}
var evenDigits = [];
for (i = 1; i < reverseArr.length; i += 2) {
evenDigits.push(reverseArr[i]);
}
for (i = 0; i < evenDigits.length; i++) {
evenDigits[i] = evenDigits[i] * 2;
if (evenDigits[i] > 9) {
var temp = evenDigits[i].toString();
var firstInt = Math.round(temp[0]);
var secondInt = Math.round(temp[1]);
evenDigits[i] = firstInt + secondInt;
}
}
var B = 0;
for (i = 0; i < evenDigits.length; i++) {
B += evenDigits[i];
}
var sum = A + B;
if (sum % 10 == 0) {
console.log('Yes');
} else console.log('No');
}
In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
var current = numbers[j];
/...
}
JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)

How to I run a function for each piece of an array within a for loop in Javascript?

I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop

repeat appendChild x times

I have this simple code wrapped inside a function:
slots = timeset / 2;
var oneslot = document.createElement("option");
document.getElementById('presentingslots').appendChild('oneslot');
the variable slots changes obviously. I want to appendChild oneslot x times where x = slots
How would I go about this?
If slots is small, you can get away with appending each element in a loop:
slots = timeset / 2;
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
document.getElementById('presentingslots').appendChild(oneslot);
}
If slots can be large, then you'll want use a DocumentFragment:
slots = timeset / 2;
var df = document.createDocumentFragment();
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
df.appendChild(oneslot);
}
document.getElementById('presentingslots').appendChild(df);
This will be more efficient since the DOM is only updated once.
Try this:
slots = timeset / 2;
for (var i = 0; i < slots; i += 1) {
var oneslot = document.createElement("option");
document.getElementById('presentingslots').appendChild('oneslot');
}
You can use a loop (for, while) to do this.
slots = timeset / 2;
var presentingslots = document.getElementById('presentingslots');
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
presentingslots.appendChild(oneslot);
}
A simple for loop would do the trick. And you can set the value as well as the text that is shown.
var slots = timeset / 2,
el = document.getElementById('presentingslots');
for (var i = 0; i < slots; i++) {
var oneslot = document.createElement('option');
oneslot.text = i;
oneslot.value = 'set my value if you want';
el.appendChild(oneslot);
}
I made a simple jsFiddle to show.

Categories

Resources