Convert object to HTML element
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
Convert javascript object into HTML
Using some more ES6 syntactic sugar like object destructuring and a template literal, you can make a very simple recursive implementation:
const convertObj = ({ node, children = [] }) => `<div class="${node}">${children.map(convertObj).join(' ')}</div>`
const tree = {node: 'A', children:[{node : 'B'}, {node: 'C', children: [{node: 'D'}]}]}
console.log(convertObj(tree))
How to convert from a DOM Object to html?
From the HTMLDocument
that parseFromString()
gives you, you can retrieve the its documentElement
and then that element's innerHTML
.
console.log(html.documentElement.innerHTML);
Note that the markup may become normalized to make it a valid document, so you may end with more than you started:
var markup = '<span>Foo</span>';
var parser = new DOMParser();
var doc = parser.parseFromString(markup, 'text/html');
console.log(doc.documentElement.innerHTML);
// "<head></head><body><span>Foo</span></body>"
Or, have corrections made for you:
var markup = '<table><div>Foo</div></table>';
// ...
console.log(doc.documentElement.innerHTML);
// "<head></head><body><div>Foo</div><table></table></body>"
converting a javascript string to a html object
You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..
string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call
but still, it would not be found by the getElementById
because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.
You would need to use append
or appendTo
or after
etc.. to put it in the dom first..
Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..
How can I convert HTML to Object structure with text and formatting?
You can use recursion. And this seems a good case for a generator function. As it was not clear which tags should be retained in format
(apparently, not p
), I left this as a configuration to provide:
const formatTags = new Set(["b", "big", "code", "del", "em", "i", "pre", "s", "small", "strike", "strong", "sub", "sup", "u"]);
function* iterLeafNodes(nodes, format=[]) {
for (let node of nodes) {
if (node.nodeType == 3) {
yield ({text: node.nodeValue, format: format.length ? [...format] : null});
} else {
const tag = node.tagName.toLowerCase();
yield* iterLeafNodes(node.childNodes,
formatTags.has(tag) ? format.concat(tag) : format);
}
}
}
// Example input
const strHTML = "<p>Hello World</p><p>I am a text with <strong>bold</strong> word</p><p><strong>I am bold text with nested <em>italic</em> Word.</strong></p>"
const nodes = new DOMParser().parseFromString(strHTML, 'text/html').body.childNodes;
let result = [...iterLeafNodes(nodes)];
console.log(result);
How can I convert object HTMLButtonElement to html button?
In the dom, Button is stored as instances of HTMLButtonElement object, that is why when you try to convert it to string(calling toString()
) you are getting [object HTMLButtonElement]
.
Since you want to add the button to the view(dom tree), you can just append the button instance to the tree using appendChild() like
var btn = document.createElement('button');btn.innerText = 'this button';document.getElementById('container').appendChild(btn);document.getElementById('markup').innerText = btn.outerHTML;
<div id="container"></div><pre id="markup"></pre>
Convert react JSX object to HTML
Use renderToStaticMarkup method - it produces HTML strings that we can transfer to the wire quickly:
const htmlString = ReactDOMServer.renderToStaticMarkup(
<div ...
);
Related Topics
Javascript Regex: Replace Hyphen Between Characters Only (Not Spaces)
How to Make Autoplay of the Swiper Slider Start Only After the Slider Enters Viewport
How to Write an Onclick Function for a Dynamically Generated Button
How to Mute Video With JavaScript or Jquery
Show Multiple Divs on Button Click
Looping Through a Json Object Containing More Objects and Arrays
How to Wait for Element to Disappear in Cypress
Jquery Click Events Firing Multiple Times
Reactjs: Expected Onclick Listener to Be a Function, Instead Got Type String
How to Count the Entire Number of Rows in a Datatable
Download Image as File in Typescript
Syntaxerror: Unexpected Token O in Json At Position 1
Json to CSV Flattening Nested Json
Export Array of Objects into Excel Using JavaScript
Discord.Js Sending Message to Specific Channel
Lodash Group by Multiple Properties If Property Value Is True