0

I started learning web developing for fun a couple weeks ago and I'm creating a rock-paper-scissors game using HTML, CSS and JS. I'm trying to add something to a block of HTML, but failing to do so with my current code. After a lot of googling I decided to try posting my question.

I added the function I'm trying to add the lines from and the place I'm trying to add them to. As I said, my code is not working and I don't quite understand why.

function displayPlayedRounds(winner) {
    "use strict";
//    <p class="roundCountPrev">
//        <img src="/images/whiteRock.png" class="player1PrevRound"/>
//            &larr; Round 4
//        <img src="/images/blackPaper.png" class="player2PrevRound"/>
//    </p>
    var middlePart, toAppend;
    if (winner === -1) {
        middlePart = "Round " + movesMade + " &rarr;";
    } else if (winner === 1) {
        middlePart = "&larr; Round " + movesMade;
    } else {
        middlePart = "Round " + movesMade;
    }
    
    toAppend = "<p class='roundCountPrev'><img src=" + userImages[userChoice] + " class='player1PrevRound'/>" + middlePart + "<img src=" + compImages[compMove] + "class='player2PrevRound'/></p>";
    document.getElementById('displayPrevRounds').prepend('toAppend');
}
<span id='displayPrevRounds' class="player1">Previous rounds
    <p class="roundCountPrev">
        <img src="/images/whiteRock.png" class="player1PrevRound"/>&larr; Round 4
        <img src="/images/blackPaper.png" class="player2PrevRound"/>
    </p>
</span>
Kert
  • 101
  • 2
  • 15

2 Answers2

1

prepend is a jquery function, create a jquery object

$('#displayPrevRounds').prepend(toAppend);
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
1

firstly, as @madalin ivascu says, prepend is a jQuery function, not comes from DOM methods.

if you want use jQuery, it does a convenient way, you need "import/require/include" jQuery first. like:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

then, you can use this:

$('#displayPrevRounds').prepend(toAppend);

note that, no '', it's a var not chr.

if you want use DOM methods anyway, you can... actually, i found you question via Google:"document html prepend",

use DOM Method:

parentNode.insertBefore(newChild, refChild);

How can I implement prepend and append with regular JavaScript?

and, here:

Append and Prepend without JQuery?

Community
  • 1
  • 1
CodeUnsolved
  • 120
  • 1
  • 9
  • Thank you for going through all this trouble, I changed what you and @madalin ivascu both said, but it is still not displaying the line I'm telling it to. I tried both of the ways you included in your comment. Any thoughts? – Kert Sep 20 '16 at 10:32
  • for your easy going, you can try jQuery all the way. i create a demo here [1wvdnfmo](https://jsfiddle.net/1wvdnfmo/3/), you can try it on. you may got problems around trigger function displayPlayedRounds – CodeUnsolved Sep 20 '16 at 13:14