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 Introducing ES2015 ES2015 Basics Template Strings

Owa Aquino
Owa Aquino
19,277 Points

Template Strings alternative for appendChild?

Just a curious, can Template Strings be an alternative for your appendChild? For example if you want to create/add a new element using javascript to your list item upon clicking a button. Can we use template string instead? If yes what will be the consequences(speed / readability)?

1 Answer

Steven Parker
Steven Parker
231,236 Points

No, you cannot use template strings as a substitute for appendChild.

As the name might suggest, template strings produce strings, but appendChild attaches a DOM node to the document. These are different functionalities, using different types of arguments.

But you might use template strings as an argument to createElement, since it takes a string argument. Perhaps doing something like this example:

let tagName = "p";
let newElement = document.createElement(`${tagName}`);
document.body.appendChild(newElement);
Owa Aquino
Owa Aquino
19,277 Points

Hi Steven,

This is noted. I'm just curious if we can make use of it as that way.

Thank you for the information!

Erika Suzuki
Erika Suzuki
20,299 Points

But then the user could just simply type p inside the createElement method instead of going into the trouble of interpolating. This is probably more useful for creating jQuery element block.

Example:

var myName = 'Erika';
var $el = $(`
    <h1>Hi, my name is ${myName}</h1>
`);