Szablon template i cloneNode
Tworzenie, wstawianie i usuwanie elementów - JavaScript na stronach WWW (HTML/CSS/JS)
Większy fragment, np. kartę produktu, wygodnie jest zapisać w HTML w znaczniku `<template>`: jego zawartość nie jest wyświetlana. Skrypt kopiuje ją (`content.cloneNode(true)`, `true` = razem z dziećmi), wypełnia kopię danymi przez `querySelector` i wstawia na stronę. Wygląd karty jest w HTML i CSS, a skrypt dokłada tylko dane.
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Karty</title>
<style>
body { font-family: sans-serif; max-width: 36em; line-height: 1.4; }
input, select, button, textarea { font: inherit; padding: 0.2em 0.4em; }
table { border-collapse: collapse; }
th, td { border: 1px solid #94a3b8; padding: 0.2em 0.6em; }
.card { display: inline-block; border: 1px solid #94a3b8; border-radius: 8px; padding: 0 1em; margin: 0.3em; }
</style>
</head>
<body>
<template id="card">
<div class="card">
<h3 class="name"></h3>
<p class="price"></p>
</div>
</template>
<div id="cards"></div>
<script>
const PRODUCTS = [
{ name: 'Zeszyt', price: 4.5, qty: 3 },
{ name: 'Plecak', price: 89, qty: 1 },
{ name: 'Długopis', price: 2.99, qty: 10 },
{ name: 'Linijka', price: 3.2, qty: 2 },
];
const template = document.getElementById('card');
for (const product of PRODUCTS) {
const card = template.content.cloneNode(true);
card.querySelector('.name').textContent = product.name;
card.querySelector('.price').textContent = product.price.toFixed(2) + ' zł';
document.getElementById('cards').append(card);
}
</script>
</body>
</html>Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu JavaScript na stronach WWW·Zaloguj się, aby zapisać postęp na koncie.