I still don’t understand the use of embedding HTML into javascript code. I understand the use of template literals to insert HTML but still not understand why is there a need to embed HTML.
Please tell me what are we trying to achieve by embedding HTML using template literals.
const setPlayerCards = (arr = players) => {
playerCards.innerHTML += arr.map(({ name, position, number, isCaptain, nickname }) =>
`<div class="player-card">
<h2>${isCaptain ? "(Captain)" : ""} ${name}</h2>
<p>Position: ${position}</p>
<p>Number: ${number}</p>
<p>Nickname: ${nickname !== null ? nickname : "N/A"}</p>
</div>`).join("");
};
2
Answers
You can use the tag to embedding HTML!
Events javascript is the same things
Let’s break down this question to the core.
Why Javascript?
HTML is a markup language which is static. So without JS you can not build anything dynamic. There are a few options with CSS to add some dynamic things but these are very limited.
An important thing to also notice is that without JS, you will always need a page reload to get new information.
Why embedding HTML code?
Sometimes you want to change your view on a HTML page. To follow your example given: We want to change a team, we make an call to the backend with JS to get those players and then we rerender the page.
Imagine having a team with more reserve players or two captains. With the previous rendered HTML, we can not place this anywhere. So it’s better to rerender the HTML needed to display this.
But why literals?
This makes it way easier to create HTML inside JS because we don’t need to concatenate everything. This improves readability and ease of use.