1

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));
    });
  }
3
  • 3
    You're going to have to clone the element you want repeated. replaceWith(existingDomElement) is going to move the existing element to the new place, not clone it Commented Nov 23, 2018 at 15:49
  • Please show your html. Commented Nov 23, 2018 at 15:50
  • Do you use duplicated id's to identify the letters? If so that's your problem. I'd need to be unique. Will be a lot easier to help you if you show your html. Or even better create a snippet that reproduces your problem. Commented Nov 23, 2018 at 15:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.