Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

document.getElementbyId is not finding element added by a fetch

I have a chat program that adds an element to the dom when messaged. This element adds properly, but when I go to query it from the dom it shows as null. I do a fetch to the server just before, but it has an await to slow it down. Any ideas?

Here is my javascript code

        socket.on('receive_message', async function(data) {
            let messaged_user_li = document.getElementById('messaged_user_li'+data['from_user']);
            console.log('messaged_user_li: '+messaged_user_li)
            if (messaged_user_li == null) {
                console.log('if fired')
                await fetch('/get_messaged_user/'+data['from_user']).then((response) => {
                    response.json().then((data2) => {
                        loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
                    });
                });
                console.log(data['from_user'])
                messaged_user_li = document.getElementById('messaged_user_li'+data['from_user']);
                //despite this element being added this log shows nulls which causes issues later on in the code.
                console.log('messaged_user_li: '+messaged_user_li)     
            }
            
            let message_user = document.getElementById('message_user'+data['from_user']);

            let message_target = document.getElementById("message_target"+data['from_user']);
            if (messaged_user_li.classList.contains('active') == false) {
                messaged_user_li.classList.add('flash-message');
            }
            if (message_user != null) {
                data = `
                <li class="clearfix">
                    <div class="message-data text-right">
                        <span class="message-data-time">just now</span>
                    </div>
                    <div class="message other-message float-right">`+data['message']+`</div>
                </li>`;
                message_target.innerHTML += data;
                //Move scroller to bottom when message received
                myDiv = message_user.querySelector(".chat-history");
                myDiv.scrollTop = myDiv.scrollHeight;
            }
        });

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are only waiting for this promise to complete:

await fetch('/get_messaged_user/'+data['from_user']).then((response) => {
    // ...
});

Not this one inside the callback:

response.json().then((data2) => {
    loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
});

Which is why your code continues executing and trying to get the added element (which hasn’t been added yet).

To solve this, you could chain the then calls:

await fetch('/get_messaged_user/'+data['from_user'])
    .then((response) => response.json())
    .then((data2) => loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen));

Or use await again:

const response = await fetch('/get_messaged_user/'+data['from_user']);
const data2 = await response.json();
loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading