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
Your code looks correct and seems to work fine when copied into a snippet:
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:
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.
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..
EDIT: