Technologies:
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?
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>
const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
button.addEventListener("click", function() {
clickEvent(param);
});
});
Answers(2)
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 OverflowTolerim
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 tag at the end of the tag or by wrapping your code in an event listener that waits for the DOMContentLoaded event:
document.addEventListener('DOMContentLoaded', function() {
const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
button.addEventListener("click", function() {
clickEvent(param);
});
});
});
Also, make sure that your query selector is written correctly and that there are no typos or misspelled class names.