1

I am trying to add a variable inside another variable which is a block of html code. It seems that you cannot just type in the name of the variable into the html code.

<body>

    <div id="wrapper"></div>

    <script>
    var link = "https://google.com"
    var codeBlock = '<a href="link">' +
    'LINK TO GOOGLE' +
    '</a>';

    document.getElementById("wrapper").innerHTML = codeBlock
    </script> 

</body>

I want the result to be a link to https://google.com.

Duncan Leung
  • 142
  • 1
  • 11

1 Answers1

0

You can use template literals for that:

const link = 'https://stackoverflow.com';
const linktext = 'stackoverflow';

const link1 = 'https://google.com';
const linktext1 = 'google.com';

// template literals
let codeblock = `<a href="${link}">${linktext}</a>`;

// or string concatenation
codeblock += '<a href="' + link1 + '">' + linktext1 + '</a>';

document.getElementById('wrapper').innerHTML = codeblock;
a {  margin: 10px; }
<div id="wrapper"></div>
d-h-e
  • 2,478
  • 1
  • 10
  • 18
  • Thanks that helped (indirectly) I ended up doing something like: var codeBlock=link to google – Duncan Leung Mar 31 '19 at 02:43
  • Ah ok, now i understand. I have edit my answer. You can see a running example with both syntaxes. The first one (template literals ES6) is more readable in my opinion. If you don't need IE11 support, i would use this syntax. – d-h-e Mar 31 '19 at 07:28