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

100
Views
How can I create a function that creates any html element with any type of attributes?

I want to create a method that takes in an element type and any number of attribute types. For example,

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

or

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

This is what I have so far but I was just wondering if there's a better way to do it

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>

By removing the attributes list the function now accepts any string as attribute. since "on" might appear in other attributes, In this example I've changed it into a more unique identifier.

As for the function itself, it's up to you. You can define a full function or a function name. Just don't write it as text and try to convert it later to code. Try to avoid this if you can.

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!