Computer Science

DomContentLoaded

In JavaScript, DOMContentLoaded is an event that is fired when the browser has completely loaded the HTML document and created the DOM tree (i.e., when all elements on the page are accessible).

How does it work


• This event fires before any images, CSS files, or external resources are loaded.
• In other words, it only comes into play when the HTML is parsed and the DOM is ready.
• This way, you can safely access DOM elements without having to write your JS code before the closes.

                        document.addEventListener("DOMContentLoaded", () => {
    document.getElementById("username").value = "misafir";
});
                    

Example


• Used to Assign Default Values
• Automatically fill form inputs when the page opens