Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Append same HTMLDivElement inside two divs

How do I append same HTMLDivElement inside two divs? In the example below only the enemyGrid is filled with divs (or only userGrid if I change the order)
Am I missing something?

const gridRows = 10
const gridCols = 10
const userGrid = document.querySelector('.user-grid')
const enemyGrid = document.querySelector('.enemy-grid')

generateGrids()

function generateGrids() {
  for (let i = 0; i < gridRows; i++) {
    for (let j = 0; j < gridCols; j++) {
      const cell = document.createElement('div')

      cell.classList.add('cell')
      cell.dataset.row = i
      cell.dataset.col = j

      userGrid.appendChild(cell)
      enemyGrid.appendChild(cell)
    }
  }
}
.grid-container {
  display: flex;
  justify-content: center;
  min-width: 900px;
}

.grid {
  width: 20em;
  height: 20em;
  display: flex;
  flex-wrap: wrap;
  margin: 4em;
  box-sizing: content-box;
  border: 1px solid #b4b4ff;
  position: relative;
}
<div class="grid-container">
  <div class="grid user-grid"></div>
  <div class="grid enemy-grid"></div>
</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Calling appendChild on an element which is already in the DOM will move the original element to the new position.

Instead, clone the element, then append:

const gridRows = 10
const gridCols = 10
const userGrid = document.querySelector('.user-grid')
const enemyGrid = document.querySelector('.enemy-grid')

generateGrids()

function generateGrids() {
  for (let i = 0; i < gridRows; i++) {
    for (let j = 0; j < gridCols; j++) {
      const cell = document.createElement('div')

      cell.classList.add('cell')
      cell.dataset.row = i
      cell.dataset.col = j

      userGrid.appendChild(cell.cloneNode(true))
      enemyGrid.appendChild(cell.cloneNode(true))
    }
  }
}
.grid-container {
  display: flex;
  justify-content: center;
  min-width: 900px;
}

.grid {
  width: 20em;
  height: 20em;
  display: flex;
  flex-wrap: wrap;
  margin: 4em;
  box-sizing: content-box;
  border: 1px solid #b4b4ff;
  position: relative;
}
<div class="grid-container">
  <div class="grid user-grid"></div>
  <div class="grid enemy-grid"></div>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!