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
171,242 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
19,026 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>
`);