I want to create cards and render them. For that I use <template>
tag.
<div class="card">
<div class="card-header">
<span class="card-name"></span>
<span class="card-cost"></span>
</div>
<img class="card-image" src="" alt="" />
<p></p>
<!-- template for table -->
<table class="card-stats"></table>
<div class="card-footer">
<span class="card-priority"></span>
<span class="card-attack-and-defence"></span>
</div>
</div>
</template>
Everything is fine but here <table>
tag should fetch from the api which is an object. It should loop through object and create
<tr>
<th></th>
<td></td>
</tr>
and append it inside <table>
tag until loop finishes.
In my code I have rendered the cards but I am unable to render the table can you help me ?
Here is the code to render card :
function renderCardItem(hero) {
const $template = document
.querySelector("#hero-template")
.content.firstElementChild.cloneNode(true);
$template.querySelector(".card-header .card-name").innerText = hero.name;
$template.querySelector(".card-header .card-cost").innerText =
hero.cost;
$template.querySelector(".card-image").src = hero.image.url;
$template.querySelector(".card-image").alt = hero.name;
$template.querySelector("p").innerText = hero.biography.alignment;
// stats
// const $statTable = $template.querySelector("#table-template"); // creating a template method
// renderTable(".card-stats", hero.powerstats); // using createElement tag
// footer part
$template.querySelector(".card-footer .card-priority").innerText = hero.priority;
$template.querySelector(".card-footer .card-attack-and-defence").innerText =
`${hero.attack}/${hero.defence}`;
return $template;
}
function renderCard($container, hero) {
const $heroItem = renderHeroItem(hero);
$container.insertAdjacentHTML("beforeend", $heroItem.outerHTML);
}
I have tried using creating a clone of the table using a inner <template>
tag but i couldn’t.
<template id="table-template">
<table class="card-stats"></table>
</template>
here cloning the firstElementChild
and looping through the object creating tr,td,th
.
but at last i use this method but also i failed to get table :
function renderTable($statTable, powerStats) {
for (const key in powerStats) {
const $tr = document.createElement("tr");
const $th = document.createElement("th");
const $td = document.createElement("td");
$th.innerText = key;
$td.innerText = powerStats[key];
$tr.insertAdjacentHTML("beforeend", $th);
$tr.insertAdjacentHTML("beforeend", $td);
$statTable.insertAdjacentHTML("beforeend", $tr);
}
}
I got :
TypeError: $statTable.insertAdjacentHTML is not a function
Is this method good or should i use template
inside a template
to achieve this can you provide me the code please ?
Holasoy Mas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.