Thẻ HTML <template>

Định nghĩa và cách sử dụng thẻ <template>

Thẻ <template> được sử dụng làm nơi chứa một số nội dung HTML ẩn khỏi người dùng khi load trang. Ví dụ sau sử dụng <template> để giữ một số nội dung sẽ bị ẩn khi load trang. Sử dụng JavaScript để hiển thị nó:

<button onclick="showContent()">Show hidden content</button>

<template>
  <h2>Flower</h2>
  <img src="img_white_flower.jpg" width="214" height="204">
</template>

<script>
function showContent() {
  let temp = document.getElementsByTagName("template")[0];
  let clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

Nội dung bên trong <template> có thể được hiển thị sau bằng JavaScript.

Bạn có thể sử dụng thẻ <template> nếu bạn có một số code HTML muốn sử dụng lại nhiều lần, nhưng chỉ nên sử dụng cho đến khi bạn yêu cầu. Để thực hiện việc này mà không cần thẻ <template>, bạn phải tạo code HTML bằng JavaScript để ngăn trình duyệt hiển thị code.

Hỗ trợ trình duyệt

Phần tử
<template>
Google ChromeMS EdgeFirefoxSafariOpera
26.013.022.08.015.0

Thuộc tính Global

Thẻ <template> cũng hỗ trợ thuộc tính Global trong HTML.

Các ví dụ khác

Điền vào trang web một phần tử div mới cho mỗi mục trong một mảng. Code HTML của từng phần tử div nằm bên trong phần tử template:

<template>
  <div class="myClass">I like: </div>
</template>

<script>
let myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
  let temp, item, a, i;
  temp = document.getElementsByTagName("template")[0];
  item = temp.content.querySelector("div");
  for (i = 0; i < myArr.length; i++) {
    a = document.importNode(item, true);
    a.textContent += myArr[i];
    document.body.appendChild(a);
  }
}
</script>

Kiểm tra sự hỗ trợ của trình duyệt cho <template>:

<script>
if (document.createElement("template").content) {
  document.write("Your browser supports template!");
} else {
  document.write("Your browser does not supports template!");
}
</script>
Chủ Nhật, 21/04/2024 08:53
51 👨 85
0 Bình luận
Sắp xếp theo
    ❖ HTML