Matthew Lo
Matthew Lo

Reputation: 11

edit 'value px' in elemtn.style.width px using Javascript

I got a function which gets the size from the user and creates the div, but I'm not sure how to express the size in front of px.

function createDiv(size) {
  const div = document.createElement("div");
  div.classList.add("box");
  div.style.width = `${size} px`;
  div.style.height = `${size} px`;
  console.log(size);

  return div;
}

It works if I input the size as 75px:

function createDiv(size) {
  const div = document.createElement("div");
  div.classList.add("box");
  div.style.width = "75px";
  div.style.height = "75px";
  console.log(size);

  return div;
}

Upvotes: 0

Views: 321

Answers (1)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8188

You need to remove the space between the value and px, it should be like this: ${size}px.

function createDiv(size) {
  const div = document.createElement("div");
  div.classList.add("box");
  div.style.width = `${size}px`;
  div.style.height = `${size}px`;
  document.body.appendChild(div);
}

createDiv(100);
.box {
  background: lawngreen;
}

Upvotes: 1

Related Questions