idcamn
idcamn

Reputation: 15

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);
  });
}

Upvotes: 0

Views: 303

Answers (3)

tehsis
tehsis

Reputation: 1612

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");
}

Upvotes: 1

Ollie
Ollie

Reputation: 1435

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);
}

Upvotes: 2

DoubleJG
DoubleJG

Reputation: 83

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>

Upvotes: 1

Related Questions