Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write JavaScript variable in a html div id inside double quotation in Template literal?

I have this code:

        const newDiv = document.createElement('div');
        newDiv.innerHTML = `
            <button class='btn btn-download'>
                <span class='icon'>&#8681;</span>
                Download Subtitle
            </button>
            <span>as</span>
            <select id=`outputFormatSelectId`>
                <option value="text">Text</option>
                <option value="text-with-time">Text with Time</option>
                <option value="json">JSON</option>
                <option value="srt">SRT</option>
            </select>`;

Notice <select id="outputFormatSelectId"> has a id outputFormatSelectId. Actually this id is a variable which has a value. But I don’t understand how can put this variable inside **id= **

Though it’s not the full code, but just the related code. If something is unclear please ask me for clarification.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Actually my confusion is about Template literal. While the code block is inside a template literal, then how can i use another variable in this template literal?

>Solution :

As @David said in comment, you need to something like this:

<select id="${outputFormatSelectId}">

So your corrected code will be:

const newDiv = document.createElement('div');
newDiv.innerHTML = `
<button class='btn btn-download'>
    <span class='icon'>&#8681;</span>
    Download Subtitle
</button>
<span>as</span>
<select id="${outputFormatSelectId}">
    <option value="text">Text</option>
    <option value="text-with-time">Text with Time</option>
    <option value="json">JSON</option>
    <option value="srt">SRT</option>
</select>`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading