CodeGym /Cours /Frontend SELF FR /Travailler avec les attributs et les styles

Travailler avec les attributs et les styles

Frontend SELF FR
Niveau 41 , Leçon 3
Disponible

4.1 Manipulation des attributs

Manipuler les attributs et les styles des éléments DOM — c'est une partie importante du travail avec les documents web. Ça permet de modifier l'apparence des éléments et leur comportement en fonction des actions de l'utilisateur ou d'autres conditions.

1. Obtenir des attributs

Pour obtenir les valeurs des attributs d'un élément, on utilise la méthode getAttribute().

Exemple :

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); // Affichera : https://example.com
          </script>
        </body>
      </html>
    
  

2. Définir des attributs

Pour définir ou modifier la valeur d'un attribut d'un élément, on utilise la méthode setAttribute().

Exemple :

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')); // Affichera : https://newexample.com
          </script>
        </body>
      </html>
    
  

3. Supprimer des attributs

Pour supprimer un attribut d'un élément, on utilise la méthode removeAttribute().

Exemple :

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')); // Affichera : null
          </script>
        </body>
      </html>
    
  

4. Vérification de la présence d'attributs

Pour vérifier la présence d'un attribut, on utilise la méthode hasAttribute().

Exemple :

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')); // Affichera : true
            link.removeAttribute('target');
            console.log(link.hasAttribute('target')); // Affichera : false
          </script>
        </body>
      </html>
    
  

4.2 Manipulation des classes

1. Ajouter des classes

Pour ajouter une classe à un élément, on utilise la méthode classList.add().

Exemple :

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. Supprimer des classes

Pour supprimer une classe d'un élément, on utilise la méthode classList.remove().

Exemple :

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. Basculer des classes

Pour basculer une classe, on utilise la méthode classList.toggle(). Elle ajoute la classe si elle n'existe pas, et la supprime si elle existe.

Exemple :

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'); // Ajoute la classe. Au clic suivant, la supprime.
            });
          </script>
        </body>
      </html>
    
  

4. Vérification de la présence d'une classe

Pour vérifier la présence d'une classe, on utilise la méthode classList.contains().

Exemple :

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')); // Affichera : true
            paragraph.classList.remove('highlight');
            console.log(paragraph.classList.contains('highlight')); // Affichera : false
          </script>
        </body>
      </html>
    
  

4.3 Manipulation des styles

1. Modifier les styles en ligne

Pour modifier les styles en ligne d'un élément, on utilise la propriété style.

Exemple :

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. Obtenir les styles calculés

Pour obtenir les styles calculés actuels d'un élément, on utilise la méthode window.getComputedStyle().

Exemple :

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); // Affichera : rgb(0, 0, 255) ou bleu
            console.log(styles.fontSize); // Affichera : 18px
          </script>
        </body>
      </html>
    
  

3. Supprimer les styles en ligne

Pour supprimer les styles en ligne, il suffit d'attribuer une chaîne vide.

Exemple :

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>
    
  
Commentaires
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION