Question

I have a for loop like this:

for(var i = 0; i < woord.length; i++) {
  if(woord[i] === letter) {
    goed = true;
    woordContainer.innerHTML[i] = woord[i];
  }
}

But the text in the woordContainer doesn't change on the page. I tried logging woord[i] to the console and it show the correct letter.

EDIT:

Let me share the complete code, so you can understand it better: (it is a hangman game)

var store, 
    woord, 
    wrapper, 
    woordContainer, 
    letterInput, 
    gokButton, 
    pogingen, 
    pogingenText;

window.onload = function() {
  store = new Persist.Store("galgje");
  woord = store.get("woord");

  pogingen = 10;

  wrapper = document.getElementById("wrapper");
  woordContainer = document.getElementById("woordContainer");
  letterInput = document.getElementById("letterInput");
  gokButton = document.getElementById("gokButton");
  pogingenText = document.getElementById("pogingenText");

  if (!woord) {
    document.location.href = "./index.html";
  }

  for (var i = 0; i < woord.length; i++) {
    woordContainer.innerHTML += ".";
  }

  wrapper.appendChild(woordContainer);

  gokButton.onclick = function() {

    var letter = letterInput.value.toLowerCase();
    var goed = false;

    if(letter) {
      for(var i = 0; i < woord.length; i++) {
        if(woord[i] === letter) {
          goed = true;
          woordContainer.innerHTML = woord[i];
        }
      }

      if(!goed) {
        pogingen--;

        if(pogingen ===  0) {
          document.location.href = "./af.html";
        }

        pogingenText.innerHTML = "Pogingen: " + pogingen;
      }

      letterInput.value = "";
    }

    return false;    
  }
}
Was it helpful?

Solution

If you want to replace the character int woordContainer.innerHTML at index i, with the one in woord[i], you can do it like this:

if(woord[i] === letter) {
    goed = true;
    var temp = woordContainer.innerHTML
    woordContainer.innerHTML = temp.substr(0, i) + woord[i] + temp.substr(i + woord[i].length);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top