Kert
Kert

Reputation: 101

Prepending constructed variable to HTML in JS

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>

Upvotes: 0

Views: 209

Answers (2)

CodeUnsolved
CodeUnsolved

Reputation: 120

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?

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

prepend is a jquery function, create a jquery object

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

Upvotes: 1

Related Questions