skip to Main Content

I have a HTML code where I’m trying to apply a gray background on HTML with JavaScript.

The body contains two divs with the wrapper class. On ul with the ID liste1 and liste2 for the second. Each of my ul contains 4 <li> items.

I tried the following script but it did nothing:

  <script>
    //When the page loads, apply the fondgris class to all li elements.
    var liste1 = document.getElementById("liste1");
    for (var i = 0; i < liste1.children.length; i++) {
        liste1.children[i].className = "fondgris";
    }
    
  </script>

Also I called my script in the header of my .html file. Should I add a function to make the code work?

3

Answers


  1. Your code looks correct and seems to work fine when copied into a snippet:

    //When the page loads, apply the fondgris class to all li elements.
    var liste1 = document.getElementById("liste1");
    for (var i = 0; i < liste1.children.length; i++) {
      liste1.children[i].className = "fondgris";
    }
    li {
      margin: 10px
    }
    .fondgris {
      background-color: gray
    }
    <ol id="liste1">
      <li>First item</li>
      <li>Second item</li>
      <li>third item</li>
    </ol>

    You might be running into the issue that the HTML hasn’t finished loading before your script runs. Try either adding the Defer property to the script tag or listen for the DOMContentLoaded event to ensure the HTML you wish to modify has loaded.

    As pointed out in the comments, using the "defer" attribute requires you to save the code in your script tag as a separate file and use the "src" attribute.

    For a "DOMContentLoaded" implementation, simply wrap your code in an event listener callback like this:

    addEventListener("DOMContentLoaded", (event) => {
      //When the page loads, apply the fondgris class to all li elements.
      var liste1 = document.getElementById("liste1");
      for (var i = 0; i < liste1.children.length; i++) {
        liste1.children[i].className = "fondgris";
      }
    });
    li {
      margin: 10px
    }
    
    .fondgris {
      background-color: gray
    }
    <ol id="liste1">
      <li>First item</li>
      <li>Second item</li>
      <li>third item</li>
    </ol>

    You could also move your script tag to the bottom of the Body tag. That way the rest of the HTML above the script tag should have already been parsed by the browser when your script is run.

    Login or Signup to reply.
  2. Your code probably won’t ever work as you intended.

    You should iterate over the elements only when the document is ready (at least interactive).

    Also, you’re seeking and managing the element wrongly…

    The snippet below is a good way to achieve what you’re intending..

    function updateListTags ( elementIds )
    {
      if ( ! Array.isArray(elementIds) ) elementIds = [elementId];
      
      for ( const elementId of elementIds )
      {
        for ( const theElement of document.querySelectorAll('#' + elementId + ' li') )
        {
          // Add a custom class.
          theElement.classList.add('myClass');
        }
      }
    }
    
    document.addEventListener
    (
      'readystatechange', readyEvent =>
      {
        // Execute the function when the document is ready.
        if ( document.readyState == 'interactive' )
        {
          updateListTags(['a1', 'a2']);
        }
      }
    );
    .myClass
    {
      font-family: monospace;
      background-color: lightgray;
    }
    <div>
      <ul id="a1">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
    <div>
      <ol id="a2">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ol>
    </div>

    EDIT:

    1. Changed the code to reflect exactly what the code in the question try to do.
    Login or Signup to reply.
  3. <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Apply Class</title>
        <style>
            .fondgris {
                background-color: gray;
            }
        </style>
    </head>
    <body>
    
        <div class="wrapper">
            <ul id="liste1">
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
                <li>Item 4</li>
            </ul>
            <ul id="liste2">
                <li>Item A</li>
                <li>Item B</li>
                <li>Item C</li>
                <li>Item D</li>
            </ul>
        </div>
    
        <script>
            window.onload = function() {
                var liste1 = document.getElementById("liste1");
                for (var i = 0; i < liste1.children.length; i++) {
                    liste1.children[i].className = "fondgris";
                }
            };
        </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search