Tarea anterior
Buscar y modificar elementos del DOM9/12
A la lista de tareas
  1. 1. Usar la propiedad textContent
  2. 2. Cambiar el texto de un elemento
  3. 3. Descomentar el script
  4. 4. Obtener el valor del campo con input.value
  5. 5. Unir textos con concatenación
  6. 6. Conectar varios archivos JavaScript
  7. 7. Crear una variable contador
  8. 8. Incrementar y disminuir valores
  9. 9. Comprobar una clase con classList.contains
  10. 10. Usar la estructura condicional if
  11. 11. Usar else y la rama alternativa
  12. 12. Cambiar el valor desde el marcado
Siguiente tarea
  • Cursos
  • Registro
  • Iniciar sesión

Loading…
En unos segundos, estará listo.

  • Teoría
  • Teoría

Comprobar una clase con classList.contains

¡Excelente! Ya tienen un contador de Me gusta cuyo valor aumenta con cada clic. Pero esa cantidad no debería limitarse a crecer.

Si la persona usuaria todavía no ha marcado Me gusta, entonces al hacer clic en el «corazón» el contador debe aumentar. Pero si el Me gusta ya existe, entonces el clic debe disminuir el contador. ¿Cómo distinguimos una situación de la otra?

Podemos comprobar si el elemento heart tiene la clase added. Si todavía no la tiene, se agrega el Me gusta. Si la clase ya está presente, se quita.

Para comprobar si un elemento tiene una clase usamos el método classList.contains:

elemento.classList.contains('clase');

Entre los paréntesis se indica la clase cuya presencia queremos comprobar. El método classList.contains devuelve true si el elemento tiene esa clase y false si no la tiene.

Los valores true y false se conocen como valores booleanos.

Veamos cómo funciona classList.contains: hagan que JavaScript muestre en la consola el valor que devuelve este método y hagan clic varias veces en el «corazón» para alternar la clase.

Todos los archivos
    <!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="setting.css"> <link rel="stylesheet" href="style.css"> <title>FlashNews!</title> </head> <body class="page light-theme"> <header class="page-header"> <div class="container"> <span class="header-logo"> <img src="img/main-logo.svg" width="67" height="29" alt="Logotipo del portal FlashNews!"> </span> <button class="theme-button" type="button">Cambiar tema</button> </div> </header> <main class="inner-news"> <article class="container"> <h1 class="inner-heading">🔥 ¡Impacto! ¡Escándalo! ¡Sensación!</h1> <div class="news-full"> <img src="img/news-robot2.jpg" alt="Robot de vacaciones"> <div class="news-stats"> <button class="heart" type="button"><span class="likes-number"></span></button> <time datetime="2019-12-22">22 dic 2019</time> </div> <p>Resulta que, para empezar a programar en JavaScript, no hace falta ser un gato. Un grupo de científicos creó el primer robot capaz de desarrollarse y cambiar su propio código. Enseguida aprendió a maquetar sitios web y se fue a trabajar como freelance a Bali.</p> </div> </article> </main> <footer class="page-footer"> <div class="container"> <p>© FlashNews!</p> <span class="footer-logo"> <img src="img/white-logo.svg" alt="Logotipo del portal FlashNews!"> </span> </div> </footer> <script src="themes.js"></script> <script src="likes.js"></script> </body> </html>
    /* Estilos de la página de noticias */ .comment-form { display: flex; margin-bottom: 30px; padding: 20px 12px; } .comment-inner { position: relative; flex-grow: 1; margin-right: 10px; } .comment-label { position: absolute; top: -16px; left: -9px; padding: 4px 8px; font-size: 10px; line-height: 14px; } .comment-field { width: 100%; height: 30px; padding: 0 10px; border: none; background-color: transparent; font: inherit; font-size: 14px; line-height: 30px; } .comment-field::placeholder { color: #aaaaaa; font: inherit; font-size: 14px; font-style: italic; } .comment-field:focus::placeholder { font-size: 0; } .comment-field:hover::placeholder, .comment-field:active::placeholder { opacity: 0.5; } .inner-news .inner-heading { margin-bottom: 20px; font-size: 24px; } .news-full { display: flex; flex-direction: column; margin-bottom: 24px; } .news-full img { margin-bottom: 4px; width: 100%; height: 220px; object-fit: cover; } .news-full .news-stats { display: flex; justify-content: space-between; } .news-full .heart { padding: 12px 10px; min-width: 40px; min-height: 34px; font-family: inherit; font-weight: bold; font-size: 16px; border: none; background-color: transparent; background-repeat: no-repeat; background-position: 12px; cursor: pointer; } .heart .likes-number { margin-left: 24px; line-height: 14px; } .news-full time { margin-top: 14px; margin-right: 12px; margin-bottom: 8px; margin-left: 0; } .news-full p { margin-top: 0; margin-right: 12px; margin-bottom: 16px; margin-left: 12px; font-size: 14px; line-height: 24px; } .comment-feed h2 { margin-top: 0; margin-bottom: 12px; } .comment-list { margin-top: 0; margin-right: 0; margin-bottom: 12px; margin-left: 0; padding: 0; list-style: none; counter-reset: comments; } .comment-list li { margin-bottom: 6px; padding: 10px 12px; min-height: 36px; font-size: 14px; line-height: 24px; } .comment-list .user-comment { position: relative; display: flex; } .comment-list .user-comment::before { counter-increment: comments; content: "#" counter(comments); padding-right: 12px; margin-right: 12px; border-right: 1px solid; font-weight: bold; } .comment-list .user-comment::after { position: absolute; content: ""; width: 0; height: 0; bottom: 0; left: -8px; border: 4px solid; border-left-color: transparent; border-top-color: transparent; } @keyframes comment-blink-light { 0% { background-color: #b6aaff; opacity: 0; } 20% { opacity: 0.8; } } @keyframes comment-blink-light-after { 0% { border-right-color: #b6aaff; border-bottom-color: #b6aaff; opacity: 0; } 20% { opacity: 0.8; } } @keyframes comment-blink-dark { 0% { background-color: #473c8d; opacity: 0; } 20% { opacity: 1; } } @keyframes comment-blink-dark-after { 0% { border-right-color: #473c8d; border-bottom-color: #473c8d; opacity: 0; } 20% { opacity: 1; } } /* Temas */ .dark-theme .header-logo { filter: invert(1) hue-rotate(180deg) brightness(2); } /* Tema claro */ .light-theme { color: #333333; background-color: #eae9f2; } .light-theme .page-header { background-color: #ffffff; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2); } .light-theme .header-link { color: #6653d9; } .light-theme .header-link::before { background-image: url("img/arrow-back-light.svg"); background-repeat: no-repeat; background-position: 0 0; } .light-theme .theme-button { color: #6653d9; border: 1px solid #6653d9; } .light-theme .theme-button::before { background-image: url("img/moon-normal.svg"); } .light-theme .theme-button:focus, .light-theme .theme-button:hover { color: #ffffff; background-color: #6653d9; } .light-theme .theme-button:focus { outline-color: #b6aaff; } .light-theme .theme-button:focus::before, .light-theme .theme-button:hover::before { background-image: url("img/moon-hover.svg"); } .light-theme .menu-open { background-color: #ffffff; background-image: url("img/menu-open-light.svg"); } .light-theme .menu:focus { outline-color: #b6aaff; } .light-theme .menu-open:focus, .light-theme .menu-open:hover { background-color: #6653d9; background-image: url("img/menu-open-dark.svg"); } .light-theme .menu-close { background-color: #6653d9; } .light-theme .menu-close:focus, .light-theme .menu-close:hover { background-color: #473c8d; } .light-theme .main-menu { background-color: #6653d9; color: #ffffff; } .light-theme .main-menu a:focus, .light-theme .main-menu a:hover { background-color: #473c8d; } .light-theme .main-menu a:focus { outline-color: #b6aaff; } .light-theme .news-view button { border: 1px solid #6653d9; color: #6653d9; } .light-theme .news-view button:focus, .light-theme .news-view button:hover, .light-theme .news-view button:active, .light-theme .news-view .view-checked { background-color: #6653d9; color: #ffffff; } .light-theme .news-view button:focus { outline-color: #b6aaff; } .light-theme .news-view .row-view:focus::before, .light-theme .news-view .row-view:hover::before, .light-theme .news-view .row-view:active::before { background-image: url("img/rows-light-checked.svg"); } .light-theme .news-view .tile-view:focus::before, .light-theme .news-view .tile-view:hover::before, .light-theme .news-view .tile-view:active::before { background-image: url("img/tiles-light-checked.svg"); } .light-theme .row-view::before { background-image: url("img/rows-light.svg"); } .light-theme .tile-view::before { background-image: url("img/tiles-light.svg"); } .light-theme .row-view.view-checked::before { background-image: url("img/rows-light-checked.svg"); } .light-theme .tile-view.view-checked::before { background-image: url("img/tiles-light-checked.svg"); } .light-theme .new-block { background-color: #ffffff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .light-theme .news-full { background-color: #ffffff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .light-theme .new-block time { color: #aaaaaa; } .light-theme .news-full time { color: #aaaaaa; } .light-theme .cookies-agreement { background-color: #fdeacd; box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.2); } .light-theme .button { background-color: #6653d9; color: #ffffff; } .light-theme .button:focus, .light-theme .button:hover { background-color: #473c8d; } .light-theme .button:focus { outline-color: #b6aaff; } .light-theme .page-footer { background-color: #6653d9; color: #ffffff; } .light-theme .subscription, .light-theme .comment-form { background-color: #ffffff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .light-theme .subscription-message { background-color: #6653d9; color: #eae9f2; } .light-theme .subscription-message::before { background-image: url("img/icon-ok-light.svg"); } .light-theme .subscription-label, .light-theme .comment-label { color: #6653d9; } .light-theme .subscription-email, .light-theme .comment-field { border: 1px solid #eae9f2; color: #333333; } .light-theme .heart { color: #6653d9; background-image: url("img/icon-heart-light.svg"); opacity: 0.7; } .light-theme .heart.added { background-image: url("img/icon-heart-light-added.svg"); } .page .heart:focus, .page .heart:hover { opacity: 1; } .light-theme .heart:focus { outline-color: #b6aaff; } .light-theme .heart:active { opacity: 1; background-image: url("img/icon-heart-light-active.svg"); } .light-theme .comment-list li { background-color: #ffffff; } .light-theme .user-comment:not(:first-child) { animation: comment-blink-light 600ms ease-in; } .light-theme .user-comment::before { border-right-color: #eae9f2; color: #cdcdcd; } .light-theme .user-comment::after { border-right-color: #ffffff; border-bottom-color: #ffffff; } .light-theme .user-comment:not(:first-child)::after { animation: comment-blink-light-after 600ms ease-in; } .light-theme .comment-label { background-color: #ffffff; } .light-theme .comment-field:focus { outline-color: #b6aaff; } /* Tema oscuro */ .dark-theme { color: #f2f2f2; background-color: #17161a; } .dark-theme .page-header { background-color: #373540; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6); } .dark-theme .header-link { color: #9484f2; } .dark-theme .header-link::before { background-image: url("img/arrow-back-dark.svg"); background-repeat: no-repeat; background-position: 0 0; } .dark-theme .theme-button { color: #9484f2; border: 1px solid #9484f2; } .dark-theme .theme-button::before { background-image: url("img/sun-normal.svg"); } .dark-theme .theme-button:focus, .dark-theme .theme-button:hover { color: #17161a; background-color: #9484f2; } .dark-theme .theme-button:focus { outline-color: #6653d9; } .dark-theme .theme-button:focus::before, .dark-theme .theme-button:hover::before { background-image: url("img/sun-hover.svg"); } .dark-theme .menu:focus { outline-color: #6653d9; } .dark-theme .menu-open { background-color: #373540; background-image: url("img/menu-open-dark.svg"); } .dark-theme .menu-open:focus, .dark-theme .menu-open:hover { background-color: #473c8d; background-image: url("img/menu-open-dark.svg"); } .dark-theme .menu-close { background-color: #473c8d; } .dark-theme .menu-close:focus, .dark-theme .menu-close:hover { background-color: #6653d9; } .dark-theme .main-menu { background-color: #473c8d; color: #f2f2f2; } .dark-theme .main-menu a:focus { outline-color: #6653d9; } .dark-theme .main-menu a:focus, .dark-theme .main-menu a:hover { background-color: #6653d9; } .dark-theme .news-view button { border: 1px solid #9484f2; color: #9484f2; } .dark-theme .news-view button:focus { outline-color: #6653d9; } .dark-theme .news-view button:focus, .dark-theme .news-view button:hover, .dark-theme .news-view button:active, .dark-theme .news-view .view-checked { background-color: #9484f2; color: #17161a; } .dark-theme .news-view .row-view:focus::before, .dark-theme .news-view .row-view:hover::before, .dark-theme .news-view .row-view:active::before { background-image: url("img/rows-dark-checked.svg"); } .dark-theme .news-view .tile-view:focus::before, .dark-theme .news-view .tile-view:hover::before, .dark-theme .news-view .tile-view:active::before { background-image: url("img/tiles-dark-checked.svg"); } .dark-theme .row-view::before { background-image: url("img/rows-dark.svg"); } .dark-theme .tile-view::before { background-image: url("img/tiles-dark.svg"); } .dark-theme .row-view.view-checked::before { background-image: url("img/rows-dark-checked.svg"); } .dark-theme .tile-view.view-checked::before { background-image: url("img/tiles-dark-checked.svg"); } .dark-theme .new-block { background-color: #2a2930; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .news-full { background-color: #2a2930; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .new-block time { color: #888888; } .dark-theme .news-full time { color: #888888; } .dark-theme .cookies-agreement { background-color: #473c8d; box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .button { background-color: #9484f2; color: #17161a; } .dark-theme .button:focus { outline-color: #6653d9; } .dark-theme .button:focus, .dark-theme .button:hover { background-color: #b6aaff; } .dark-theme .page-footer { background-color: #0a0910; color: #f2f2f2; } .dark-theme .subscription, .dark-theme .comment-form { background-color: #2a2930; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .subscription-message { background-color: #9484f2; color: #17161a; } .dark-theme .subscription-message::before { background-image: url("img/icon-ok-dark.svg"); } .dark-theme .subscription-label, .dark-theme .comment-label { color: #9484f2; } .dark-theme .comment-label { background-color: #2a2930; } .dark-theme .subscription-email, .dark-theme .comment-field { border: 1px solid #473c8d; color: #f2f2f2; } .dark-theme .heart { color: #9484f2; background-image: url("img/icon-heart-dark.svg"); opacity: 0.7; } .dark-theme .heart:focus { outline-color: #6653d9; } .dark-theme .heart.added { background-image: url("img/icon-heart-dark-added.svg"); } .dark-theme .heart:active { opacity: 1; background-image: url("img/icon-heart-dark-active.svg"); } .dark-theme .comment-list li { background-color: #2a2930; } .dark-theme .user-comment:not(:first-child) { animation: comment-blink-dark 600ms ease-in; } .dark-theme .user-comment::before { border-right-color: #17161a; color: rgba(255, 255, 255, 0.3); } .dark-theme .user-comment::after { border-right-color: #2a2930; border-bottom-color: #2a2930; } .dark-theme .user-comment:not(:first-child)::after { animation: comment-blink-dark-after 600ms ease-in; } .dark-theme .comment-field:focus { outline-color: #6653d9; }
    let heart = document.querySelector('.heart'); let likesNumber = document.querySelector('.likes-number'); let counter = 0; heart.onclick = function () { // Agreguen el código aquí counter++; likesNumber.textContent = counter; heart.classList.toggle('added'); };
    let page = document.querySelector('.page'); let themeButton = document.querySelector('.theme-button'); themeButton.onclick = function () { page.classList.toggle('light-theme'); page.classList.toggle('dark-theme'); };

    El código ha cambiado, haz clic en "Actualizar" o activa la ejecución automática.

    Ha ido a otra página

    Haga clic dentro del mininavegador para poner el foco en esta ventana.

    100%
    Consola
    ObjetivosRealizado
    0
      1. En la línea 6, escriban la instrucción console.log(heart.classList.contains('added'));.
      2. Hagan clic en el «corazón».
      3. Abran la consola. En el momento del clic, el elemento todavía no tenía la clase added, por eso se mostró false.
      4. Vuelvan a hacer clic en el «corazón».
      5. Abran la consola. En el momento del clic, el elemento sí tenía la clase added, por eso se mostró true.

      © 2023-2026, codigoheroe.com