PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] How to append elements to all items in an array

 May 12, 2022     append, arrays, dom, javascript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing