简体   繁体   中英

How to create child element and move it inside parent?

I'm trying to create Tic-Tac-Toe game and the problem now is that I'm creating svg element when empty area is clicked, but don't know how to move it inside the parent (and how to make that child element). Need your help, thanks!

let clickableAreas = document.querySelectorAll('.clickable-area');
let step = true;

function clickArea(e) {
  if(step) {
    let img = document.createElement('img');
    img.src = './images/cross.svg';
    step = false;
  }
  else {
    let img = document.createElement('img');
    img.src = './images/circle.svg';
    step = true;
  }
  // testing class toggle
  e.classList.toggle("empty");
}

for(let i = 0; i < clickableAreas.length; i++) {
  document.addEventListener("click", function(event) {
    clickArea(event.target);
  });
}

Your code looks good so far. You should be able to call appendChild to add the image to the correct area.

function clickArea(e) {
  let img = document.createElement('img');
  if(step) {
    img.src = './images/cross.svg';
    step = false;
  }
  else {
    img.src = './images/circle.svg';
    step = true;
  }
  // testing class toggle
  e.classList.toggle("empty");

  // Add the image to the DOM element
  e.appendChild(img);
}

You can add an element with element.appendChild(childElement) . An example would be

const parent = document.getElementById('parent'); 

const img = document.createElement('img');
img.src = './images/circle.svg';

parent.appendChild(img);

Would result in the html looking like

<div id='parent'> 
  <img src="./images/circle.svg">
</div>

Once your element is created you need (as you have mentioned) add it to another node which will become this new element parent. For that you can use Node.appendChild(childNode) which does exactly that: appends childNode to Node

function clickArea(e) {
  let parent = e // or get your parent element.
  if(step) {
    let img = document.createElement('img');
    img.src = './images/cross.svg';
    step = false;
    parent.appendChild(img)
  }
  else {
    let img = document.createElement('img');
    img.src = './images/circle.svg';
    step = true;
    parent.appendChild(img)
  }
  // testing class toggle
  e.classList.toggle("empty");
}

I would also recommend to extract the img creation outside the if so you can avoid duplicated code:

function clickArea(e) {
  let parent = e // get your parent element.
  let img = document.createElement('img');
  if(step) {
    img.src = './images/cross.svg';
    step = false;
    parent.appendChild(img)
  }
  else {
    img.src = './images/circle.svg';
    step = true;
    parent.appendChild(img)
  }
  // testing class toggle
  e.classList.toggle("empty");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM