Vladimir Lebedev Vladimir Lebedev - 6 months ago 15
jQuery Question

Convert JSON to html element

In input of function is a JSON 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 a html element. It has to return a 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);
}

Answer

Using only javascript

 var _createElem = document.createElement(""+_elem.tag+""); 
 _createElem.innerHTML = _elem.content;

//set attributes
for(var keys in _elem.attr){
  _createElem.setAttribute(''+keys+'',_elem.attr[keys])
 }
//set style 
 for(var keys in _elem.style){
  _createElem.setAttribute(''+keys+'',_elem.style[keys])
 }
//set events
for(var keys in _elem.events){
_createElem.setAttribute('on'+keys,_elem.events[keys])
} 
document.getElementById("demoDiv").appendChild(_createElem)

Note: The elem has got both onclick & href , you may need to return true/false as per your requirement

Check this jsfiddle for demo