Issue
I'm trying to add a delete button to all items with a specific class in a menu but when I try to loop through the array of classes and append the button it can only be added to one of the items, anyone know how I can fix it?
let menuItems = document.getElementsByClassName('menu-item');
let deleteButton = document.getElementById('deleteButton');
for (var i = 0; i < menuItems.length; i++) {
menuItems[i].append(deleteButton);
};
Solution
You need to clone that element, and please don't use an ID, otherwise you'll end up having duplicated IDs.
const ELS_menuItems = document.querySelectorAll('.menu-item');
const EL_deleteButton = document.querySelector('#deleteButton');
ELS_menuItems.forEach(EL_item => EL_item.append(EL_deleteButton.cloneNode(true)));
// Be advised that you'll end up having duplicated IDs in your DOM now
- https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
- https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
- https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Answered By - Roko C. Buljan Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.