CodeGym /Cursos Java /Frontend SELF ES /Trabajo con atributos y estilos

Trabajo con atributos y estilos

Frontend SELF ES
Nivel 41 , Lección 3
Disponible

4.1 Manipulación de atributos

Manipular los atributos y estilos de los elementos del DOM es una parte importante del trabajo con documentos web. Esto permite cambiar la apariencia de los elementos y su comportamiento basado en acciones del usuario u otras condiciones.

1. Obtención de atributos

Para obtener valores de los atributos de un elemento se usa el método getAttribute().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <a href="https://example.com" id="myLink">Visit Example.com</a>

          <script>
            const link = document.getElementById('myLink');
            const href = link.getAttribute('href');
            console.log(href); // Mostrará: https://example.com
          </script>
        </body>
      </html>
    
  

2. Establecer atributos

Para establecer o cambiar el valor de un atributo de un elemento se usa el método setAttribute().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <a href="https://example.com" id="myLink">Visit Example.com</a>

          <script>
            const link = document.getElementById('myLink');
            link.setAttribute('href', 'https://newexample.com');
            console.log(link.getAttribute('href')); // Mostrará: https://newexample.com
          </script>
        </body>
      </html>
    
  

3. Eliminación de atributos

Para eliminar un atributo de un elemento se usa el método removeAttribute().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <a href="https://example.com" id="myLink" target="_blank">Visit Example.com</a>

          <script>
            const link = document.getElementById('myLink');
            link.removeAttribute('target');
            console.log(link.getAttribute('target')); // Mostrará: null
          </script>
        </body>
      </html>
    
  

4. Comprobar existencia de atributos

Para comprobar la existencia de un atributo se usa el método hasAttribute().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <a href="https://example.com" id="myLink" target="_blank">Visit Example.com</a>

          <script>
            const link = document.getElementById('myLink');
            console.log(link.hasAttribute('target')); // Mostrará: true
            link.removeAttribute('target');
            console.log(link.hasAttribute('target')); // Mostrará: false
          </script>
        </body>
      </html>
    
  

4.2 Manipulación de clases

1. Añadir clases

Para añadir una clase a un elemento se usa el método classList.add().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
          <style>
            .highlight {
              background-color: yellow;
            }
          </style>
        </head>
        <body>
          <p id="myParagraph">This is a paragraph.</p>

          <script>
            const paragraph = document.getElementById('myParagraph');
            paragraph.classList.add('highlight');
          </script>
        </body>
      </html>
    
  

2. Eliminar clases

Para eliminar una clase de un elemento se usa el método classList.remove().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
          <style>
            .highlight {
              background-color: yellow;
            }
          </style>
        </head>
        <body>
          <p id="myParagraph" class="highlight">This is a paragraph.</p>

          <script>
            const paragraph = document.getElementById('myParagraph');
            paragraph.classList.remove('highlight');
          </script>
        </body>
      </html>
    
  

3. Alternar clases

Para alternar una clase se usa el método classList.toggle(). Añade una clase si no está, y la elimina si está.

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
          <style>
            .highlight {
              background-color: yellow;
            }
          </style>
        </head>
        <body>
          <button type="button" id="myButton">Click me!</button>

          <script>
            const btn = document.getElementById('myButton');
            btn.addEventListener("click", () => {
              btn.classList.toggle('highlight'); // Añade clase. Al hacer clic de nuevo la elimina.
            });
          </script>
        </body>
      </html>
    
  

4. Comprobar existencia de clase

Para comprobar la existencia de una clase se usa el método classList.contains().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
          <style>
            .highlight {
              background-color: yellow;
            }
          </style>
        </head>
        <body>
          <p id="myParagraph" class="highlight">This is a paragraph.</p>

          <script>
            const paragraph = document.getElementById('myParagraph');
            console.log(paragraph.classList.contains('highlight')); // Mostrará: true
            paragraph.classList.remove('highlight');
            console.log(paragraph.classList.contains('highlight')); // Mostrará: false
          </script>
        </body>
      </html>
    
  

4.3 Manipulación de estilos

1. Cambiar estilos en línea

Para cambiar los estilos en línea de un elemento se usa la propiedad style.

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <p id="myParagraph">This is a paragraph.</p>

          <script>
            const paragraph = document.getElementById('myParagraph');
            paragraph.style.color = 'red';
            paragraph.style.fontSize = '20px';
          </script>
        </body>
      </html>
    
  

2. Obtener estilos calculados

Para obtener los estilos calculados actuales de un elemento se usa el método window.getComputedStyle().

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
          <style>
            #myParagraph {
              color: blue;
              font-size: 18px;
            }
          </style>
        </head>
        <body>
          <p id="myParagraph">This is a paragraph.</p>

          <script>
            const paragraph = document.getElementById('myParagraph');
            const styles = window.getComputedStyle(paragraph);
            console.log(styles.color); // Mostrará: rgb(0, 0, 255) o color azul
            console.log(styles.fontSize); // Mostrará: 18px
          </script>
        </body>
      </html>
    
  

3. Eliminar estilos en línea

Para eliminar estilos en línea, basta con establecer el valor del estilo en una cadena vacía.

Ejemplo:

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <p id="myParagraph" style="color: red; font-size: 20px;">This is a paragraph.</p>

          <script>
            const paragraph = document.getElementById('myParagraph');
            paragraph.style.color = '';
            paragraph.style.fontSize = '';
          </script>
        </body>
      </html>
    
  
Comentarios
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION