Home > OS >  Html generator from json appendchild to the wrong parent
Html generator from json appendchild to the wrong parent

Time:11-02

I am coming to you today, I tried to make an html generator from a json file in javascript. The problem being that arrived at a certain moment the children "appendChild" to the previous element instead of "appendChild" to the parent

here is my code :

$(document).ready(function(){
    $.getJSON('THE JSON FILE FROM URL', function(data){
        const components = data.htmlComponents.tableSuiviCommandes.components;
        createHtmlFromJson(components)
    }).fail(function( jqxhr, textStatus, error ) {
        var err = textStatus   ", "   error;
        console.log( "Request Failed: "   err );
    });



    function createHtmlFromJson(json, parent){
        json.forEach(jsonElement => {
            // log("jsonElemement", jsonElement)
            createdElement = document.createElement(jsonElement.balise);
            if(jsonElement.content) createdElement.innerHTML = jsonElement.content;

            jsonElement.attributes?.forEach(element => {
                createdElement.setAttribute(element.name, element.content);
            });
            
            if(!parent){
                document.body.appendChild(createdElement);
            }else {
                parent.appendChild(createdElement);
            }
            
            jsonElement.childs?.forEach(element => {
                let theParent = createdElement;
                if(element != typeof Array) element = [element];
                createHtmlFromJson(element, theParent);
            });
        
        });
    }


    function log(name, value){
        console.log("----------");
        console.log(name);
        console.log(value);
        console.log("----------")
    }
});

the json file :

{
    "htmlComponents": {
        "tableSuiviCommandes": {
            "components": [
                {
                    "balise": "div",
                    "attributes": [
                        {
                            "name": "class",
                            "content": "containerTable"
                        }
                    ],
                    "childs": [
                        {
                            "balise": "table",
                            "childs": [
                                {
                                    "balise": "thead",
                                    "childs": [
                                        {
                                            "balise": "tr",
                                            "childs": [
                                                {
                                                    "balise": "th",
                                                    "content": "Id"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Statut"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Voir la demande"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Objet"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Projet/Application"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Demandeur(s)"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Site"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Expression de besoin"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Référence interne"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "CDC retenu"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "N°Cotation"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "N°Devis"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Date devis"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "N°DEMAP"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "N°CMD"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "N°GAFI"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Date prévisionnelle de livraison"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Date de livraison"
                                                },
                                                {
                                                    "balise": "th",
                                                    "content": "Commentaire"
                                                }
                                            ]
                                        }
                                    ]
                                },
                                {
                                    "balise": "tbody",
                                    "attributes": [
                                        {
                                            "name": "id",
                                            "content": "tableauSuivi"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    }
}

the html generate :

enter image description here

I tried with the debbuger to make step by step, but I really don't understand why theParent is not really the parent so that the children are children of the previous element

CodePudding user response:

I'd suggest extracting a logic of creating a single HTML element into separate function. It may simplify things in terms of understanding. Here is a createElement function based on your createHtmlFromJson function, but it creates only single element (and all of its children of course) and just returns it:

function createElement(component) {
    const el = document.createElement(component.balise);

    if (component.content) {
        const text = document.createTextNode(component.content);
        el.appendChild(text);
    }

    component.attributes?.forEach((attr) => {
        el.setAttribute(attr.name, attr.content);
    });

    component.childs?.forEach((child) => {
        // Create all of its children and append them to this element
        el.appendChild(createElement(child));
    });

    return el;
}

Now you can create an array of HTML elements based on your JSON, like so:

const { components } = data.htmlComponents.tableSuiviCommandes;
// Transform each object into the actual HTML element via `.map()`
const arrayOfHTMLElements = components.map(createElement);

And then you can append it to the DOM, like so:

arrayOfHTMLElements.forEach((element) => {
  document.body.appendChild(element);
});

CodePudding user response:

// You try this code    
$(document).ready(function () {
                
                createHtmlFromJson(JSON.parse(json).htmlComponents.tableSuiviCommandes.components)
    
    
    
                function createHtmlFromJson(json, parent) {
                    // console.log(json);
                    json.forEach(jsonElement => {
                        // log("jsonElemement", jsonElement)
                        createdElement = document.createElement(jsonElement.balise);
                        if (jsonElement.content) createdElement.innerHTML = jsonElement.content;
    
                        jsonElement.attributes?.forEach(element => {
                            createdElement.setAttribute(element.name, element.content);
                        });
    
                        if (!parent) {
                            document.body.appendChild(createdElement);
                        } else {
                            parent.appendChild(createdElement);
                        }
    
                        let theParent = createdElement;
                        jsonElement.childs?.forEach(element => {
                            // console.log(createdElement);
                            if (element != typeof Array) element = [element];
    
                            // console.log(theParent);
                            createHtmlFromJson(element, theParent);
                        });
    
                    });
                }
    
    
                
            });
  • Related