简体   繁体   中英

Access an element appended after DOM has loaded

I am creating an Input box and a submit button after the DOM has loaded but I can't seem to access them after appending

textInput = document.createElement('input');

textInput.setAttribute("id", "myMessage");
textInput.setAttribute("type", "text");
textInput.setAttribute("name", "message");

submitButton = document.createElement('input')

submitButton.setAttribute("id", "sendbutton");
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("name", "submit");
submitButton.setAttribute("value", "Send");

document.getElementById("msgInput").append(textInput)
document.getElementById("msgInput").append(submitButton)

I am trying to access it this way to capture the events keypress , keyup and onclick .

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById("myMessage").addEventListener('keypress', handleKeyPress);
    document.getElementById("myMessage").addEventListener('keyup', handleKeyUp);

    document.querySelector('#sendbutton').onclick = () => {
        var data = {'msg': document.querySelector('#myMessage').value, 'username': username };
        append_msgs(data);
        document.querySelector('#myMessage').value = '';
    }
});

Try console.log(document.querySelector('#myMessage')) inside your function, and see what that returns. While it doesn't fix your issue, it might help you use the Inspector Tools ( F12 in Chrome) Console in order to figure out what's going on. Have you tried using getElementById instead of querySelector for testing purposes?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM