14. Custom elements

Versión para imprimir.

En esta lección se presentan los custom elements.

A. Custom element

Ejemplo

Salida

Ábrelo en otra pestaña.

Revísalo en gilpgedit.

1<!DOCTYPE html>
2<html lang="es">
3
4<head>
5 <meta charset="UTF-8">
6 <meta name="viewport"
7 content="width=device-width">
8 <title>Custom elements</title>
9 <style>
10 elemento-1 {
11 color: blue;
12 }
13
14 elemento-2 {
15 display: block;
16 background-color: aqua;
17 }
18 </style>
19</head>
20
21<body>
22 <h1>Custom elements</h1>
23 <elemento-1>Hola</elemento-1>
24 <elemento-1>
25 <em>Saludos</em>
26 </elemento-1>
27 <elemento-2>
28 Estoy de buenas 😁
29 </elemento-2>
30</body>
31
32</html>

B. Los custom element en acción

Ejemplo

Salida

Ábrelo en otra pestaña.

Revísalo en gilpgedit.

1<!DOCTYPE html>
2<html lang="es">
3
4<head>
5 <meta charset="UTF-8">
6 <meta name="viewport"
7 content="width=device-width">
8 <title>Acción</title>
9 <script>
10 class Elemento3
11 extends HTMLElement {
12 connectedCallback() {
13 this.innerHTML = /* html */
14 `Estoy volando🚁
15 <strong>
16 alto
17 </strong>.`
18 this.addEventListener("click",
19 () => this.clic())
20 }
21 clic() {
22 alert("ouch")
23 }
24 }
25 customElements.define(
26 "elemento-3", Elemento3)
27 </script>
28 <style>
29 elemento-3 {
30 cursor: pointer;
31 }
32 </style>
33</head>
34
35<body>
36 <h1>Acción</h1>
37 <elemento-3></elemento-3>
38 <p>Saludos desde la tierra.</p>
39 <elemento-3></elemento-3>
40</body>
41
42</html>

C. Uso de atributos

Ejemplo

Salida

Ábrelo en otra pestaña.

Revísalo en gilpgedit.

1<!DOCTYPE html>
2<html lang="es">
3
4<head>
5 <meta charset="UTF-8">
6 <meta name="viewport"
7 content="width=device-width">
8 <title>Atributos</title>
9 <script>
10 class MiSaludo
11 extends HTMLElement {
12 connectedCallback() {
13 const nombre =
14 this.getAttribute("nombre")
15 const alegre =
16 this.hasAttribute("alegre")
17 const icono =
18 alegre ? "😄" : "🖐"
19 this.innerHTML = /* html */
20 `${icono}
21 hola
22 <strong>${nombre}</strong>.`
23 }
24 }
25 customElements.define(
26 "mi-saludo", MiSaludo)
27 </script>
28</head>
29
30<body>
31 <h1>Atributos</h1>
32 <p>
33 <mi-saludo nombre="pp">
34 </mi-saludo>
35 </p>
36 <p>
37 <mi-saludo nombre="tt" alegre>
38 </mi-saludo>
39 </p>
40</body>
41
42</html>

D. Resumen