Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
How to get position to be absolute rather than 'undefined' after using setAttribute

I am attempting to assign properties from an array called 'spell' to newly created img elements housed within a div container.

for (let i = 0; i <spell.length; i++){
          let styles = spell[i]
          let container = document.getElementById('imagecontainer');
          let newImg = document.createElement('img');

          let top = styles.top;
          let left = styles.left;
          let imgSrc = styles.src;
          newImg.setAttribute('width','25px');
          newImg.setAttribute('left',left);
          newImg.setAttribute('top',top);
          newImg.setAttribute('src',imgSrc);
          newImg.setAttribute('height','25px')
          newImg.setAttribute('position','absolute');
            console.log(newImg.position)
          container.appendChild(newImg);
        }

however, when I run the code it logs newImg.position as undefined for all images. I'm not sure what is wrong

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Set the properties of the style attribute: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

const spell = [{
  top: "10px",
  left: "10px",
  src: "foo.png"
}, {
  top: "50px",
  left: "50px",
  src: "bar.png"
}];

const container = document.getElementById('imagecontainer');

for (let i = 0; i < spell.length; i++) {
  let styles = spell[i];

  let newImg = document.createElement('img');
  let top = styles.top;
  let left = styles.left;
  let imgSrc = styles.src;

  newImg.style.width = '25px';
  newImg.style.height = '25px';
  newImg.style.top = top;
  newImg.style.left = left;
  newImg.style.position = 'absolute';
  newImg.setAttribute("src", imgSrc);

  console.log(newImg.style.position);
  container.appendChild(newImg);
}
<div id="imagecontainer"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda