Problem inserting text into a Javascript div

Asked

Viewed 900 times

0

I want to change the html content of a div, putting the 1 option of an array of elements, but when I do the following code nothing happens:

<script>
    var players = ['player1', 'player2', 'player3', 'player4', 'player5', 'player6', 'player7', 'player8'];

    var teste = document.getElementById('jog1');

    teste.innerHTML = players[0];

</script>


    <div class="player top win" id ='jog1'>
      boo
    </div>

When accessing index.html, instead of "boo", it should be "player1" but continues as boo. Another question, there is how I take this "boo" from the code and only ask to add 'player1' directly in the html page?

2 answers

0

In this example, simply put the script after the html code, in this way:

<div class="player top win" id ='jog1'>
  boo
</div>

<script>
    var players = ['player1', 'player2', 'player3', 'player4', 'player5', 'player6', 'player7', 'player8'];

    var teste = document.getElementById('jog1');

    teste.innerHTML = players[0];

</script>

The browser executes the codes as it reads, and, in its code, you try to locate, in the script, an element that the browser has not yet interpreted, so nothing occurs (in fact it generates an error).

As for the second doubt, I did not understand it well, I could explain better?

  • Thanks! !

0


Probably not waiting for the document to be ready and loaded, and already trying to get the element and exchange its content, I try to do this for example in the event onload of the body:

var players = ['player1', 'player2', 'player3', 'player4', 'player5', 'player6', 'player7', 'player8'];

window.addEventListener("load", function(event) {
    var teste = document.getElementById('jog1');
    teste.innerHTML = players[0];
  });
<div class="player top win" id ='jog1'>
      boo
    </div>

  • thanks, it worked out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.