Drag and Drop with li and p elements

Hey!
Need some help if anyone knows this.
Is practicing JavaScript by making simple games. Encountered a problem in the end. I want the word to go back to the list when you started the game if you drag another word to the image that already contains words.
The word goes back but ends up in the first line of the list not in the empty space.
I’m going through for loop, apparently there’s something wrong there. Adds some pictures and codes to the game.

function moveBackToList(word) { 
    for(let i = 0; i < wordElems.length; i++){
        wordElems[i].innerHTML += "";
        wordElems[i].innerHTML = word;
        break;
    }
}

Thanks!

There is no conditional statement in the loop to check whether the list item is empty… On the first loop (i=0), the program replaces the first item in the wordElems list with word and then breaks.

Replace wordElems[i].innerHTML += “”; with an if statement and you’ll be good to go :slight_smile:

1 Like

Thanks for quick reply. Will test with this solution.

Hello again!
Tried with the variants you suggested, but it did not work with them either.
In the first option, the word is changed every time you want, but only the first line.
In the second word is changed only once even though I try to do several activities.
Sends the codes as well. I might be writing something wrong.
Thanks.

for(let i = 0; i < wordElems.length; i++){
       if(i <= 0){
           wordElems[i].innerHTML = word;
        }
        break;
        }
2)
for(let i = 0; i < wordElems.length; i++){
if(wordElems[i].innerHTML === ""){
            wordElems[i].innerHTML = word;
        }
        break;
        }
  }

To be honest, we probably need a link to the code for this project. Seeing a small snippet out of context is not always enough information to determine the problem.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Okay! Thanks for the tip! Will think about it next time.

The problem is solved! Break would be written inside the if statement. Thanks for the help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.