How to write a loop correctly?

  • 0
    Let's assume that there can be n number of blocks. I need to do the following for each block:
    1) Take the name of the block ".words-moving__calm span"
    2) Create and put 10 spans with the parent's name in each running-string-wrapp block, see paragraph 1 for a total of 20 spins
    And so for each g-project__words-moving block, and there may be no idea how many of them. The loop written below puts all the names of all the blocks in each block, which is not correct. How to write a loop correctly?
    There is an html block:
    <div class="g-project__words-moving global-flex gl-border-b th-back-color">
                            <div class="words-moving__calm global-flex words-mov-def">
                                <span class="th-color font-default">musicbad</span>
                            <div class="words-moving__running-string global-flex on-hidden words-mov-def op-none">
                                <div class="running-string-wrapp global-flex"></div>
                                <div class="running-string-wrapp global-flex"></div>

    and the code
    function createRunningString() {
        const boxes = document.querySelectorAll('.g-project__words-moving');
        const keySpans = document.querySelectorAll('.words-moving__calm span');
        const place = document.querySelectorAll('.running-string-wrapp');
        let keyWordsArray = [];
        keySpans.forEach(i => keyWordsArray.push(i.innerHTML))
        for(let i = 0; i < boxes.length; i++){ // 5 блоков с видео
            for(let j = 0; j < place.length; j++){ // 2 блока со словами
                for(let k = 0; k < 10; k++){ // Каждому блоку со словами по 10 спанов с именем этого блока
                    let span = document.createElement('span');
                    span.classList.add('th-color', 'font-default');
                    span.innerHTML = `${keyWordsArray[i]}`
    JavaScript Anonymous, May 24, 2020

  • 1 Answers
  • 0
    It would be correct not to write cycles explicitly:

    document.querySelectorAll('.g-project__words-moving').forEach(n => {
    const html = n.querySelector('.words-moving__calm span').outerHTML.repeat(10);
    n.querySelectorAll('.running-string-wrapp').forEach(m => m.innerHTML = html);

    Well, if we talk about an error in your code, then you always iterate over all the existing .words-moving__calm span elements, instead of limiting only those that lie inside the current .g-project__words element -moving . To fix this, you can move the place declaration to the beginning of the outer loop body, replacing document with boxes [i] .

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!