Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

What could be the reason for querySelectAll to give back an empty NodeList despite the fact that there ought to be three buttons?

I am trying to attach event listeners to all the buttons in my program. However, the const buttons = document.querySelectorAll('.button'); code that I have written returns an empty NodeList. Here is the HTML code for the buttons:

<div id="buttons" class="buttons">
        <button type="button" class="button" id="send">Send</button>
        <button type="button" class="button" id="delete">Delete</button>
        <button type="button" class="button" id="again">Again</button>
</div>
And here's the JavaScript code I have written to add event listeners to the buttons:

const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
    button.addEventListener("click", function() {
        clickEvent(param);
    });
});
Unfortunately, the code is not functioning as intended, and I am not sure why. Can you help me understand what's going wrong here?

Answers(2)
avatar
Vogi
a month ago
Verified Answer
The code you have written looks correct. The issue might be that the JavaScript code is being executed before the HTML code has been loaded. You can try wrapping your JavaScript code in an event listener that waits for the DOM to load before executing the code. Here's how you can do it:
document.addEventListener("DOMContentLoaded", function() {
    const buttons = document.querySelectorAll('.button');
    buttons.forEach(button => {
        button.addEventListener("click", function() {
            clickEvent(param);
        });
    });
});
This should ensure that the JavaScript code is executed only after the HTML code has been loaded.

Sources

Document: querySelectorAll() method - Web APIs | MDN - Mozilla DeveloperJavaScript querySelector: Selecting Elements By CSS SelectorsQuerySelectorAll returning an empty nodelist with OOPElement.querySelectorAll() - Web APIs | MDNjavascript - querySelectorAll returns empty nodelist - Stack Overflow
avatar
Tolerim
a month ago
Make sure that your JavaScript file is being loaded after the HTML has been parsed. You can do this by placing your