'Can't Stringify the Object that Contains DOM Elements on it
I'm trying to build an object that has an key on it and its value is html content from the dom. (I will try to send this in Back latter). But I can't do that for some reasons.
Here is how I build it.
const handlePrintOrder = () => {
const html = document.getElementById('invoice'); // this takes the elements
const body = {content: html}; // here I build the object
console.log(JSON.stringify(body)) // this gives an error
};
And here is the error:
Uncaught TypeError: Converting circular structure to JSON
--> starting at object with constructor 'HTMLElement'
| property '__reactFiber$8di0naxlmzf' -> object with constructor 'FiberNode'
--- property 'stateNode' closes the circle
I don't know if you need this but here is my dom (simpliefied, but is dynamic):
<section id='invoice'>
<div class='box'>
<hr class='linebreak' />
<div class='box_wrappers'>
<div style={{ marginRight: '8em' }}>
<div class='information-wrapper'>
<p class='information-item-title'>MARKE:</p>
{/* <p class='infromation-item-item'>${order.vehicle.brand}</p> */}
</div>
<div class='information-wrapper'>
<p class='information-item-title'>MODELL:</p>
{/* <p class='infromation-item-item'>${order.vehicle.model}</p> */}
</div>
<div class='information-wrapper'>
<p class='information-item-title'>TERMIN:</p>
{/* <p class='infromation-item-item'>${order.appointment}</p> */}
</div>
</div>
</div>
</div>
</section>
Solution 1:[1]
You cannot stringify an HTMLElement, since it contains the references to the parent Element. Since both parent and child contains each other's references, you get a circular dependency, which cannot be stringify.
To fix this you can use something like HTMLElement.outerHTML to get stringified version of HTMLElement.
So your code would be as follow:
const handlePrintOrder = () => {
const html = document.getElementById('invoice'); // this takes the elements
const body = {content: html.outerHTML }; // here I build the object
console.log(JSON.stringify(body)) // this gives an error
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashok |
