Waiting for the DOM to be ready in Javascript

waiting-for-the-dom-to-be-ready-in-javascript

When you’re working with Javascript, you’re likely to have run into a pretty common problem: if your Javascript appears before your HTML, then trying to do things like attach events to your HTML is not possible. For example, consider this code:



    
        
    
    
         id="button">Click Me
    

Even though there is a button with the ID #button, this code actually throws an error. The reason why is because the Javascript is loading before the DOM. Therefore trying to query select for #button returns null:

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at file.html:5:46

This is a pretty common problem related to DOM readiness – your HTML DOM has not loaded – so it is not ready to have Javascript applied to it.

Waiting for the DOM to be ready in Javascript

If you want to wait for the HTML to load, before your Javascript runs – then try using DOMContentLoaded. We can wrap our entire Javascript in this event listener like so:

window.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#button').addEventListener('click', () => {
        console.log('You clicked me!')
    });
});

Now, no error will be produced in your code, since the code within the DOMContentLoaded event listener will only fire once the HTML is fired. That means you can continue to have your Javascript before your HTML, and encounter no issues. Of course, you can also solve this problem by putting your Javascript after your HTML – but this is not always possible.

I hope you’ve enjoyed this quick guide to DOM Readiness and DOMContentLoaded in Javascript.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
amazing-typing-effect-using-typed.js-(javascript)

Amazing Typing Effect using Typed.js (JavaScript)

Next Post
updating-object-key-values-with-javascript

Updating Object Key Values with Javascript

Related Posts
役員変更登記

役員変更登記

2025-05-08 申請用総合ソフトで行う アカウントは個人で OK(法人用は特にない) 登記申請書(法人等用)を使う 参考 https://www.touki-kyoutaku-online.moj.go.jp/toukinet/taiken/taiken_zeninjuunin.html https://houmukyoku.moj.go.jp/homu/shogyo_online03.html 法人番号で検索した住所のハイフンが外字扱いだったので、直接入力に切り替えて入力した 電話がかかってきて以下のような文言修正を要求された 添付ファイルに電子署名が必要 議事録の「第 2 号議案:代表理事の重任について」を「第 2 号議案:理事及び代表理事の重任について」 同様に「任期満了に伴い、鈴木健志を理事及び代表理事に再任することを決議した。」 「なお席上就任を承諾した。」の文言を追加。同意書なしのため必要らしい。…
Read More