Solution 1 :

You could use a string/template literal.

document.getElementById("x").innerHTML = `<span style="color:red;">${x}</span>`;

Use backticks instead of quotes and your variable goes inside the ${}. Everything between the ticks will get interpolated into a string, including the variable inside the ${}.

Solution 2 :

Well, if all you want to do at the end of the day is change a span’s color, skip directly to method 3.

There are many ways of doing so:

1- Basic string concatenation:

document.getElementById("x").innerHTML = '<span style="color:red;">' + x + '</span>';

2- Template literals (where you need to use backticks (`) instead of quotes):

document.getElementById("x").innerHTML = x + `<span style="color:red;">${x}</span>`;

3- Why not simply use CSS to change the color? Assuming you insert your <span> directly into your HTML, and that this span has an ID of ‘mySpan’, you can do:

var span = document.getElementById('mySpan');
span.style.color = 'red';

Problem :

I’m total newbie, and i want to know how to put a var x into the span tag so i can change the color of the variable.

function wyr()
{
    var x = (Math.floor(Math.random() * 100) + 1);

    if(x <= 33)

        document.getElementById("x").innerHTML = x + '<span style="color:red;">%</span>';

    else if(x >= 34 && x <= 66)

        document.getElementById("x").innerHTML = x + '<span style="color:blue;">%</span>';

    else

        document.getElementById("x").innerHTML = x + '<span style="color:yellow;">%</span>';
}
``

Comments

Comment posted by Anis R.

And note the use of backticks (`) instead of normal quotation marks

Comment posted by Vorihs

Thank you, it worked.I didn’t knew about that, still learning 🙂

Comment posted by Korgrue

Thanks David. Updated my comment.

By