Skip to content Skip to sidebar Skip to footer

How To Use A Variable In Html Code Using Backtick In Javascript?

I have a variable there is define few value with using JavaScript backtick. How can I use another variable with backtick? Why newData variable is not readable inside? JavaScript b

Solution 1:

It is called template literals, as the documentation states:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

What you want to do is called expression interpolation what you can achieve with ${variableName}.

You need to use as the following:

const newData = 'This is new data';
const liElem = `<ul>
   <li class="${newData}">Good news</li>
   <li class="icon-text-dark-yellow">Fair</li>
   <li class="icon-text-dark-red">Poor</li>
   <li class="icon-text-light-gray">N/A</li>
</ul>`;
                    
console.log(liElem);

I hope that helps!

Solution 2:

Use placeholder ${<your var name>}

var liElem = '';
    $('button').click(function(){
    var newData = 'This is new data'

    liElem = `<ul>
                    <li class=${newData}>Good news</li>
                            <li class="icon-text-dark-yellow">Fair</li>
                            <li class="icon-text-dark-red">Poor</li>
                            <li class="icon-text-light-gray">N/A</li>
                        </ul>`;
                        
                        
    console.log(liElem);
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><button>click</button>

Solution 3:

This is not different from any regular string if you start a string with " you have to end it with ". So if you start it with ` then you need to end it with `.

So if you want to use + newData + then you have to write:

var newData = 'This is new data'
liElem = `<ul>
                <li class=" ` + newData + ` ">Good news</li>
                        <li class="icon-text-dark-yellow">Fair</li>
                        <li class="icon-text-dark-red">Poor</li>
                        <li class="icon-text-light-gray">N/A</li>
                    </ul>`;
console.log(liElem);

Or as you already use tempalte string literals can use embedded expressions<li class="${newData}">

Post a Comment for "How To Use A Variable In Html Code Using Backtick In Javascript?"