Bryan Del Bianco
Bryan Del Bianco

Reputation: 49

How can use a variable of Javascript in the "style" of tag?

i need create this function to improve my code. I need give to the a color given by the caller of the function, how can i do this?

Here the code:

function visualizza(array, div, color)
{
    div.html("");
    div.append("<p>");

    array.forEach(function (e)
    {
        div.append
        (
            "<span style='color: (here i need the variable)'>" + e.nominativo + "   Tel: "+e.cellulare+"</span><br>"
        )
    });

    div.append("</p>");
}

Upvotes: 2

Views: 58

Answers (2)

onyx
onyx

Reputation: 1618

You can use template literals which is a feature of ES2015. It enables you to inject variables into a string.

`<span style='color: ${yourColor}'>${e.nominativo} Tel: ${e.cellulare}</span><br>`

NOTE: This feature is not compatible with all browsers.

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Use concatenation like the rest of your js variables

"<span style='color: "+color+"'>" + e.nominativo + "   Tel: "+e.cellulare+"</span><br>"

Upvotes: 5

Related Questions