Could you please help me to build a html document by nested classes?
My main aim is to build a string with html markup like this
<html>
<div>
<p>123</p>
<div>
<div>
123
<a>123</a>
</div>
</div>
</div>
</html>
I have a class DOMElement
with the following fileds:
class DOMElement {
TagName :string;
TextContent: string | null;
Attributes: string[];
AttributesValue: string[];
Children: DOMElement[]; // stored nested tags;
}
So I already have a DOM structure of my document with this class, and I want to return this into markup.
For this I used an incorrect method:
public convertToHtml (domTree: DOMElement, str: string = ''): string {
if (domTree.Children.length != 0) {
domTree.Children.forEach((x) => {
let attributes = '';
x.Attributes.forEach((attr, index) => {
attributes += attr + '=' + `${x.AttributesValue[index]}"`;
});
if (x.Children.length != 0) {
x.TextContent = '';
}
str += `<${x.TagName.toLowerCase()} ${attributes}>${this.convertToHtml(
x,
str,
)}${x.TextContent}</${x.TagName.toLowerCase()}>`;
});
}
return str;
};
How to fix this recursion to make it return a markup structure? Or are there other options to create markup with a nested object?
2
Answers
I think there were several typos/small mistakes in the code that added up. Here is a working example with no real changes other than typo fixes:
Playground link
Extra Notes/Suggestions/Tips
class
vs.interface
DOMElement
was aclass
, but it could also have been aninterface
or atype
. In this case, it looks like you’re not using it as aclass
really, so a TS type is probably better.Default argument value type inference
You used
str: string = ''
as an argument, but TS can infer that it’s a string already when you specify''
as the default.This is how I handle this. I have a function I call ‘createHTMLElement’.
I create JSON objects that look like this:
And I call it like this:
The ele that is returned will be a dom object. Instead of passing a single child, it can take an array (passed as ‘children’) to add multiple at one time. Maybe this, or some tweaked version, can help you get what you’re looking for.