Search code examples
javascripthtmlfor-loopdomappendchild

How to create many elements and add them to another many elements?


Hi i have problems with creating many elements and adding to them many elements and then append them to another elements.

my code looks like this:

    const createElementsFromLocalStorage = (event) => {
        for (let i = 0; i < allRecipes.length; i++) {
            let optionValue = document.createElement('option');
            optionValue.value = allRecipes[i].title;

            for(let j = 0; j < allDaysDataLists; j++) {
                allDaysDatalists[j].appendChild(optionValue);
            }
        }
    }

So i want to create optionValue "i" times and set them values with each allRecipes.title. It should looks like this for example:

I have array allRecipes = [1, 2, 3, 4, 5] So I want to create 5 times optionValue and each optionValue should have .value depends on array index. For example: optionValue.value = 1, optionValue.value = 2, optionValue.value = 3, optionValue.value = 4, optionValue.value = 5. Then I want to append all this optionValue elements to each allDaysDataLists. So each allDaysDataLists should have all this created optionValue.


Solution

  • for(let i = 0; i < allDaysDataLists.length; i++) {
         for(let j = 0; j < allRecipes.length; j++) {
             const optionValue = document.createElement('option');
             optionValue.value = allRecipes[j].title;
             allDaysDatalists[i].appendChild(optionValue);
         } 
    }