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

216
Visualizações
JavaScript - Creating elements based on an array of object data

How can I generate an element and from just an array of object data?

Instead of this:

var element1 = document.createElement('div');
    element1.style.width = '100px';
    element1.style.height = '100px';

I want (something like) this:

element = [none, element1, element2, element3, etc];

element[1] = {name:'element1', type:'div', width:'100px', height:'100px'};

var (element[1].name) = document.createElement(element[1].type);
    (element[1].name).style.width = element[1].width;
    (element[1].name).style.height= element[1].height;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There's no native method for doing this (AFAIK), but you can try an improvised one, like

function ArrayToElements(array) {
  let elemList = {};
  for (let i of array) {
    let elem = document.createElement(i.type);
    for (let j in i.attr) {
      elem.setAttribute(j, i.attr[j]);
    }
    elemList[i.name] = elem;
  }
  return elemList;
}

This method supports all attributes, including style.
I've created a working example here.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:

const elementList = [
    { name: 'element1', type: 'div', width: '100px', height: '100px' },
    { name: 'element2', type: 'div', width: '100px', height: '100px' },
    { name: 'element1', type: 'div', width: '100px', height: '100px' }
]

const nodeList = elementList.map(el =>
    document
        .createRange()
        .createContextualFragment(
            `<${el.type} style="width: ${el.width}; height: ${el.height}">${el.name}</${el.type}>`
        )
);

You can read what document.createRange().createContextualFragment() does here, but essentially you end up with an array of nodes which you can then append to another DOM element, or the body itself.

nodeList.forEach(el => document.body.append(el));
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