I’m trying to add event listeners to all buttons in my program, but const buttons = document.querySelectorAll(‘.button’); returns an empty NodeList.
HTML:
<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>
JS:
const buttons = document.querySelectorAll('.button');
buttons.forEach(button => {
button.addEventListener("click", function() {
clickEvent(param);
});
});
This is what I have and I have no idea why it isn’t working. It should return a NodeList of the buttons but the list is empty.
2
Answers
You are using #button as the selector in document.querySelectorAll(), but your buttons have ids of send, delete, and again. The # selector is used to select elements with a specific id attribute, not elements with a specific class or tag name, so use the class button instead (. is for classes)
You are running
<script>
before the<div id="buttons">
gets inserted into the documentUse
<script defer src="...">
or place script in the end of<body>
to avoid that