Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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);
                    });
                    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>click</button>

Why newData variable is not readable inside? JavaScript backtick? Is there any way to do this?

like image 494
Rohit Verma Avatar asked Mar 20 '26 06:03

Rohit Verma


1 Answers

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!

like image 87
norbitrial Avatar answered Mar 21 '26 23:03

norbitrial