Here's my code:
function listDesserts (){
var dessertList = ["pudding", "cake", "toffee", "ice cream", "fudge", "nutella"];
var i = 0;
while (i< dessertList.length){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' +i;
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i];
ul.appendChild(nli);
i++;
}
}
Since I'm setting the li tags IDs based on the number items in my array, i sets it to zero as it should. Rather I want to modify i so that it sets the IDs beginning with 1 without it skipping the first array member. I've tried a few things but I'm missing this. Anybody?
As you are iterating an array, the counter variable should always run from 0 to length-1. Other solutions were possible, but are counter-intuitive.
If you have some one-based numberings in that array, just use i+1 where you need it; in your case 'item-'+(i+1).
Btw, you might just use a for-loop instead of while.
Use var i = 1;
and use i-1 where you currently have i
var i = 1;
while (i< dessertList.length-1){
var ul = document.getElementById("thelist");
var nli = document.createElement("li");
var nliID = 'item-' + (i-1); //<----- here
nli.setAttribute('id', nliID);
nli.setAttribute('class', 'listitem');
nli.innerHTML = dessertList[i-1]; //<----- and here
ul.appendChild(nli);
i++;
}
Related
So I'm making a simulation of the lottery. I generate 6 numbers between 0 and 40 and show them in the html id 'generated'. My problem is that if I click a second time on 'generate' (in my html page), the previous generated numbers are still a part of the array and still show up. Does anybody know how to clear the array when pushed on the button multiple times?
This is my Javascript code:
'use strict';
function generatenumbers(){
let number = [];
let i;
i=0;
for(i= 0; i <= 5; i++){
number[i] = Math.floor(Math.random()*40);
}
i = 0;
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let textnode = document.createTextNode(number[i]);
node.appendChild(textnode);
document.getElementById("generated").appendChild(node);
}
}
You are supposed to remove the previously appended children then add new ones.
var list = document.getElementById("generated");
list.removeChild(list.childNodes[0]); // for removing first child only
//for removing all children
var list = document.getElementById("genrated");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
you don't want to clear the array...you want to clear the document.getElementById("generated") element before you call the loop, that way, there will always be 6 LI elements at the end of the function.
document.getElementById("generated").innerHTML = ""; // clear the element
for(i=0; i<= number.length - 1; i++){
let node = document.createElement("LI");
let textnode = document.createTextNode(number[i]);
node.appendChild(textnode);
document.getElementById("generated").appendChild(node);
}
I have a simple array
var answerAttribute = ['A','B','C','D'];
I have 16 list items, what I'm trying to accomplish is loop through the length of the list and regardless of if the list 2 items or 300. I'd lke to have a data attribute associated with it of A,B, C or D.
Here's what I'm working with:
var questionOption = '';
for(var i = 0; i < quizContent.length; i++) {
questionOption = answerAttribute[i % answerAttribute.length];
console.log(questionOption);
}
When logging this to the console, it logs A, AB, ABC, ABCD, ABCDundefined, and keeps repeating undefined until it's reached the loops conclusion. My question is what am I doing incorrectly so that it only logs one letter per loop.
questionOption += answerAttribute[i]
This statement is short-form for questionOption = questionOption + answerAttribute[i]. It will append the next element to questionOption in every iteration of the loop.
It looks like what you want is probably questionOption = answerAttribute[i]. This will replace the value in questionOption with the new element instead of appending it.
You could simply log only the current value, like this:
var questionOption = '';
for (var i = 0; i < quizContent.length; i++) {
//what is questionOption used for?
questionOption += answerAttribute[i];
console.log(answerAttribute[i]);
}
or if you want questionOption to refer to the current value
questionOption = answerAttribute[i];
console.log(questionOption );
You're looping the quizContent indexes and applying them to the answerAttribute array. I believe what you want is a nested loop...
var quizContent = Array(10); // assume you have 10 quiz questions...
var answerAttribute = ['A','B','C','D'];
for (var i = 0; i < quizContent.length; i++) {
// generate a string for each quiz option
var questionOption = '';
for (var n = 0; n < answerAttribute.length; n++) {
questionOption += answerAttribute[n];
}
quizContent[i] = questionOption;
console.log(questionOption);
}
console.log(quizContent);
Somehow I doubt that the question is actually about the logging, and is actually about the resulting string.
Either way, I'd do this without loops.
var answerAttribute = ['A','B','C','D'];
var quizContent = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
var questionOption = answerAttribute
.join("")
.repeat(Math.ceil(quizContent.length / answerAttribute.length))
.slice(0, quizContent.length);
console.log(questionOption);
It just joins the answerAttribute into a string of characters, and repeats that string the number of times that the length of answerAttribute can be divided into quizContent.length (rounded up).
Then the final string is trimmed down to the size of the quizContent to remove any extra content from the rounding up.
Note that this approach assumes a single character per attribute. If not a single, but they're all the same length, it can be adjusted to still work.
How can I create a loop or function that will display a new array index on every click. I tried using a for loop but I keep getting only the first value and then when I'll click it'll jump to the last value.
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
function textForward (){
arrow.addEventListener('click', function(){
var arr = [
'a','b','c','d'
]
for (var i = 0; i < arr.length; i++)
para.innerHTML = arr[i]
});
}
Each time a button is clicked, the above needs to display the next value of that array in order. (for example, the array will start out at a, then when the user clicks it'll go to b, then on the next click c and so on).
Figured it out, I feel dumb for not figuring this out..Here is the updated code
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
let counter = 0;
function textForward (){
var arr = [
'How are you?',
'Are you Ready to play the Game',
'Here is how it works',
'you have three hints to guess what I am thinking',
'Guess wrong and you are out',
'simple..let the games begin'
]
para.innerHTML = arr[counter];
counter ++;
}
textForward();
You need a global counter to track the current index. Something like this
var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
// The current index
var index = 0;
var arr = ['a','b','c','d'];
arrow.addEventListener('click', function(){
para.innerHTML = arr[index];
if(index < arr.length - 1) index++;
});
I'm working on some codewars problems and I came to this 'remove noise thing', I guess the point is to escape backslash \ and use replace method, which was easy. But I didn't want to use replace, instead I found myself in trouble trying to remove items with splice method.
Funny thing is, when I debug in Chrome dev tools, step by step I see items get removed, but console.log spits out certain characters($/·|ªl) problematic to remove, and at the end gets returned and join with those characters. Why is that?
function removeNoise(str) {
var base = "%$&/#·#|º\ª";
var arr = str.split('');
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
var condition = base.indexOf(item);
if(condition + 1) {
//works like a charm
//arr[i] = '';
arr.splice(i,1);
//this thing wont work
//when debugging it removes the items from the array
//console log print no removing
}
}
return arr.join('');
}
removeNoise('he%$&/#·#|º\ª\llo'); //=> $/·|ªllo
You're using splice to remove entries from your array, but you're then incrementing i for the next loop. If you remove the entry at index 5 from a 10-entry array, what was the entry at index 6 is now at index 5 (of what's now a 9-entry array), so you don't want to increment your index.
The solution is to use a while loop and only update i if you don't splice:
function removeNoise(str) {
var base = "%$&/#·#|º\ª";
var arr = str.split('');
var i = 0;
while (i < arr.length) {
var item = arr[i];
var condition = base.indexOf(item);
if (condition + 1) {
// Remove this entry, reuse same value for 'i'
arr.splice(i,1);
} else {
// Don't remove this entry, move to next
++i;
}
}
return arr.join('');
}
var result = removeNoise('he%$&/#·#|º\ª\llo');
var pre = document.createElement('pre');
pre.appendChild(
document.createTextNode(result)
);
document.body.appendChild(pre);
You're removing characters from your array. This will throw your indexer variable i out of sync with the characters you want to test. Easy way to fix is to start at the end of the array working your way to the beginning.
Change your for loop to this.
for(var i = arr.length -; i <= 0; i--) {
function removeNoise(str) {
var base = "%$&/#·#|º\ª";
var arr = str.split('');
for(var i = arr.length - 1; i <= 0 ; i--) {
var item = arr[i];
if(base.indexOf(item) >= 0) {
//remove the offending character
arr.splice(i,1);
}
}
return arr.join('');
}
removeNoise('he%$&/#·#|º\ª\llo'); //=> $/·|ªllo
I've got a script that adds li elements to a ul and assigns some attributes to it based on a user's selection in a select element. However, I figured it would be necessary to make sure that the li element doesn't already exist in the ul. However, I'm not sure, but I think that either the array isn't assigning variables to it or there's something wrong with my if statement that compares the array. Of course, I may be totally off. I'm stumped.
function anotherCounty(){
var newCounty = document.forms['newForm'].county.value;
var ul = document.getElementById("counties");
var items = ul.getElementsByTagName("li");
var itemArray = new Array();
for (var i = 0; i < items.length; i++){
itemArray.push(items[i]);
}
if (itemArray.indexOf(newCounty)<'0'){//I've also tried ==-1 and <0
var new_item = document.createElement("li");
new_item.id = "addCounty[]";
new_item.innerHTML = newCounty;
ul.insertBefore(new_item, ul.firstChild);
}
}
You are comparing a string with DOM elements. I think this is what you actually need:
itemArray.push(items[i].value);
Instead of using indexOf, you'd be a lot better off to use this approach:
function anotherCounty() {
var newCounty = document.forms['newForm'].county.value;
var ul = document.getElementById("counties");
var items = ul.getElementsByTagName("li");
for (var i = 0; i < items.length; i++){
if(items[i].value == newCounty) return;
}
var new_item = document.createElement("li");
new_item.id = "addCounty[]";
new_item.innerHTML = newCounty;
ul.insertBefore(new_item, ul.firstChild);
}
I know this thread is old, but I just had the same issue and what worked for me was
itemArray.push(items[i].innerHTML);