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

95
Views
¿Cómo puedo crear una función que cree cualquier elemento html con cualquier tipo de atributos?

Quiero crear un método que admita un tipo de elemento y cualquier cantidad de tipos de atributos. Por ejemplo,

 createElement('div', {class: 'test-class', id: 'testId'})

o

 createElement('input', {class: 'test-class', id: 'myInput', type: 'button', onclick: 'console.log('hello world')'})

Esto es lo que tengo hasta ahora, pero me preguntaba si hay una mejor manera de hacerlo.

 function create(elementType, ...args) { const element = document.createElement(elementType); const [elementProps] = args; const { className, id, innerText, type, name, value, eventType, eventAction, } = elementProps[0]; for (let prop in elementProps[0]) { if (typeof prop !== 'undefined') { element.className = className; element.id = id; element.innerText = innerText; element.type = type; element.name = name; element.value = value; element.addEventListener(eventType, eventAction, false); } } return element; }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

 function cEl(elementType, ...args) { const element = document.createElement(elementType); const elementProps = args[0]; for (const [key, value] of Object.entries(elementProps)) { if (typeof value != 'undefined') { if (key.indexOf('listener') == 0) { // Assume this is an event. element.addEventListener(key.substr(8), value, false); } else { element.setAttribute(key, value); } } } return element; } var el = cEl('input', { class: 'test-class', id: 'myInput', type: 'button', listenerclick: function(){console.log("hello world");} // Not a script but an actual function. }); document.getElementById('d').append(el);
 <div id="d"></div>

Al eliminar la lista de atributos, la función ahora acepta cualquier cadena como atributo. dado que "on" puede aparecer en otros atributos, en este ejemplo lo he cambiado a un identificador más único.

En cuanto a la función en sí, depende de usted. Puede definir una función completa o un nombre de función. Simplemente no lo escriba como texto e intente convertirlo más tarde en código. Trate de evitar esto si puede.

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!