javascriptecmascript-6template-literals

How can I write a JavaScript variable inside double quotation marks in a 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.

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