1

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>';
}
``
0

2 Answers 2

2

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 ${}.

Sign up to request clarification or add additional context in comments.

3 Comments

And note the use of backticks (`) instead of normal quotation marks
Thank you, it worked.I didn't knew about that, still learning :)
Thanks David. Updated my comment.
1

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.