Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
JavaScript: creación de elementos basados en una matriz de datos de objetos

¿Cómo puedo generar un elemento y solo a partir de una matriz de datos de objetos?

En lugar de esto:

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

Quiero algo como esto:

 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 answers
Answer question

0

No existe un método nativo para hacer esto (AFAIK), pero puedes probar uno improvisado, como

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

Este método admite todos los atributos, incluido style .
He creado un ejemplo de trabajo aquí .

about 4 years ago · Juan Pablo Isaza Report

0

Prueba esto:

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

Puede leer lo que document.createRange().createContextualFragment() hace aquí , pero esencialmente termina con una matriz de nodos que luego puede agregar a otro elemento DOM, o al cuerpo mismo.

 nodeList.forEach(el => document.body.append(el));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!