repl.it
@todojs/

03-template-wc-countries

HTML, CSS, JS

No description

fork
loading
Files
  • index.html
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Template</title>
</head>
<body>
<template id="table">
  <table>
    <thead><tr><th>Flag</th><th>Country</th></tr></thead>
    <tbody></tbody>
  </table>
</template>
<template id="row">
  <tr><td></td><td></td></tr>
</template>
<script>
  class WCCountries extends HTMLElement {
    constructor () {
      super ();
      this.attachShadow ({mode : 'open'});
      const path  = 'https://raw.githubusercontent.com/hjnilsson/country-flags/master';
      const table       = document.querySelector('#table').content.cloneNode(true);
      const tbody       = table.querySelector ('tbody');
      const rowTemplate = document.querySelector ('#row');
      this.shadowRoot.appendChild (table);
      fetch (`${path}/countries.json`)
        .then (response => {
          if (response.status === 200) {
            return response.json ();
          }
        })
        .then (data => {
          for (let country in data) {
            const clone     = row.content.cloneNode (true);
            const tds       = clone.querySelectorAll ('td');
            const img       = document.createElement ('img');
            img.src         = `${path}/png100px/${ country.toLowerCase () }.png`;
            img.style.width = '40px';
            tds[ 0 ].appendChild (img);
            tds[ 1 ].textContent = data[ country ];
            tbody.appendChild (clone);
          }
        });
    }
  }
  customElements.define('wc-countries', WCCountries);
</script>
<wc-countries></wc-countries>
</body>
</html>
result
console
?