ondrejm
ondrejm

Reputation: 164

How to replace multiple elements with the same element in jQuery?

I am trying to make the Hangman game in the browser. I generate a random word, then display one empty box for each letter of the word, and the user will be able to click a button with a letter to try to guess if the random word contains this letter. If it does, then all empty boxes representing that letter get replaced with a box with that letter written inside.

My problem is, if the word generated contains the letter clicked multiple times, only the last occurrence gets replaced in the end, which I figured would be caused by my wrong usage of jQuery's 'replaceWith'. I hope I didn't make this sound too complicated, if you have any question, please ask away!

So here is my code:

// Get all occurences of the clicked letter and push their positions into array

  function letterClicked(id) {
    var positionsOfLetter = [];
    for (var i = 0; i < randomWord.length; i++) {
      if (randomWord[i] == id) {
        positionsOfLetter.push(i);
      }
    }
    // Replace each box at position that contains the letter clicked with a box containing the letter clicked

    positionsOfLetter.forEach(position => {
      $('#' + position).replaceWith($("#" + id));
    });
  }

Upvotes: 1

Views: 677

Answers (1)

Shushan
Shushan

Reputation: 1225

This row

$('#' + position).replaceWith($("#" + id));

returns the same element every time, causing it to move around until it settles at the last iteration of the loop. replacing it with

$('#' + position).replaceWith($("#" + id).clone());

should do the trick.

Upvotes: 2

Related Questions