Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to HTML element

In input of function is an object who has this structure:

{
  tag: 'a', //type of html object
  content: "blabal", //inner content
  attr: {
    href: "vk.com",
    id: 'someId'
  },
  events: {
    click: 'alert(this.href)',
    focus: 'this.className="active"'
  },
  style: {
    width:"100px"
  }
}

It describes an HTML element. It has to return an HTML element with specified properties. How to parse it? I have something like this:

elemen={
  tag:'a',
  content:"blabal",
  attr:{
    href:"vk.com",
    id:'someId'
  },
  events:{
   click:'alert(this.href)',
   focus:'this.className="active"'
  },
  style:{
    width:"100px"
  }
};
console.log(elemen.tag);
var node = document.createElement(elemen.tag);
node.innerHTML= elemen.content;

for(var prop in elemen.events){

  var fun =new Function(elemen.events[prop]);
  console.log(fun);
  node.bind(prop, fun);
//   divv.bind(prop, fun);
}
like image 737
Vladimir Lebedev Avatar asked May 20 '16 06:05

Vladimir Lebedev


People also ask

How convert DOM object to HTML?

document. getElementById("textarea"). value var parser = new DOMParser(); var html = parser. parseFromString(htmlString, 'text/html');

Is a HTML element an object?

In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.

How do I convert an object to text?

Convert Object to String in java using toString() method of Object class or String. valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.

How do you convert an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');


1 Answers

Use addEventListener to register events on Element and .bind(thisArg) to have specified argument as this-context

var elemen = {
  tag: 'a',
  content: "blabal",
  attr: {
    href: "vk.com",
    id: 'someId'
  },
  events: {
    click: 'alert(this.href)',
    focus: 'this.className="active"'
  }
};
var node = document.createElement(elemen.tag);
node.innerHTML = elemen.content;
for (var attr in elemen.attr) {
  node.setAttribute(attr, elemen.attr[attr]);
}
for (var prop in elemen.events) {
  node.addEventListener(prop, new Function(elemen.events[prop]).bind(node));
}
document.body.appendChild(node);
.active {
  color: red;
}
like image 170
Rayon Avatar answered Sep 20 '22 21:09

Rayon