DEV Community

artydev
artydev

Posted on

HTML to DOM (following...)

Following the previous snippet toDom, here is another example

String.prototype.toDOM = function () {
  var d = document,
    i,
    a = d.createElement("div"),
    b = d.createDocumentFragment();
  a.innerHTML = this;
  while ((i = a.firstChild)) b.appendChild(i);
  return b;
};

const users = [
  {
    prenom: "Hal",
    age: 45,
  },
  {
    prenom: "Bert",
    age: 54,
  }
];

const mail = ({ prenom, age }) =>
  `<li onclick="alert('${prenom}')">
  Bonjour ${prenom} vous avez ${age} ans
  </li>`;

const style = `
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
li:hover {
  cursor: pointer;
  background: blue;
  color: white
}`

document.body.append(
  `
  <style>
    ${style}
  </style>
  <ul>
    ${users.map(mail).join('')} 
  </ul>
  `.toDOM()
);

You can test it here : toDom

Top comments (0)