Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Setting .textContent with template literal

How come when I use a template literal to define my .textContent value I am unable to insert html into the template literal? This code returns simply 'Hello'...

<p class="desc"></p>
<script>
const p = document.querySelector('p.desc');
p.textContent = `Hello`;
</script>

This code returns my html WITH the chevrons ...

<p class="desc"></p>
<script>
const p = document.querySelector('p.desc');
p.textContent = `<a href =' #'>Hello</a>`;
</script>

1 Answer

Steven Parker
Steven Parker
231,172 Points

It sounds like your expectations of what template literals do might not be accurate. In both of your examples, you have created ordinary strings so the output is correct for what you are providing.

A typical template literal would include one or more substitution tokens that will be replaced by values determined by the code. For example:

let name = "Joe";
p.textContent = `Hello, ${name}`;  // will show "Hello, Joe"

And if you wanted to create a link on the page instead of just the word or seeing the code (including chevrons), you would update the innerHTML element instead of the textContent:

p.innerHTML = "<a href='#'>Hello</a>";

Okay thank you Steven Parker that worked! :)