Alex Stephens
Alex Stephens

Reputation: 13

putting a string value into a <p> tag from javascript

I have a program that is a three card brag game, which basically randomly selects a card using the random function to select a card from two arrays after that i've used a series of if statements decides what hand the player has.

i want to be able to get a piece of text from inside that if statement in javascript into a paragraph within the HTML.

This is an example of one of my if statements that decides one of the hands.

if(crand >= crand1 && crand >= crand2 || 
   crand1 >= crand && crand1 >= crand2 || 
   crand2 >= crand && crand2 >= crand1) {
         document.getElementById("P1").innerHTML='Player has high card';
}

this is what i have in my HTML body where i want that information to go

<p id='P1'></p>

Upvotes: 0

Views: 2826

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

Make sure that the code is in the document just before the <body> element closes (</body) so that the element can be found when your code executes.

<body>

  <p id="P1"></p>

  <script>

    // By placing your script after all the HTML elements, you 
    // ensure that they are loaded into memory by the time the
    // script runs.
    var p1 = document.getElementById("P1");

    var x = 10;

    if(x === 10){
      p1.textContent = "Hello!";
    }

  </script>
</body>

Upvotes: 1

Related Questions