Javascript: createElement vs. template literals
A few days back while building a project I got asked a question that really intrigued me to find and read about it. The question was:
“What if I used template strings instead of using createElement to create HTML elements? Does it make any difference?”
Both “document.createElement()” and “template literals” allow us to create elements so the question arises when to use what? Does it make any difference if we use any of them or replace them? You’ll find out as you keep reading.
createElement()
- The createElement() method is a DOM level-1 feature that was introduced in 1998.
- It’s old and robust but then there is redundancy when we have to create elements every now and then.
- The browser support for createElement() is good at 97.92 %.
Template literals
- Template literals were introduced in ES6 a.k.a. ECMAScript 6 in 2015.
- It’s newer faster, has less code more readability, is easy to maintain, and has fewer chances of dealing with bugs.
- The browser support for template strings is at 97.11 % which is not big of a difference when compared to createElement() but here’s the thing template literals don’t work on IE 11, Opera, and blackberry.
Note: IE 11 is retiring and won’t be accessible after February 14, 2023.
Get Anushka Shukla’s stories in your inbox
Join Medium for free to get updates from this writer.
Below is a sample code snippet to add HTML elements using createElement and template literals.
JS way
Alternative with template literals
Conclusion
As you saw even in the sample code above there is not much of a difference when we create elements using createElement() or using template strings. So the answer to the question comes down to choosing what works best for you along with the browser the users of the application are putting up with. As IE11, Opera and Blackberry do not support template strings yet, you can choose to go with createElement() method.










