Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append elements to all items in an array

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading