0

I have the website written in 'content.json' file, so my html.index has an empty body. Currently I can console.log all the elements in 'script.js' and I can see in console all the divs that I declared in 'content.json'. My question is how to append all those elements to html body so I can actually see all my divs that I've written in json?

I used recursion to get all those elements from .json and console.log() them. This is my json file (just in case). https://textuploader.com/15820

function loadJSON(callback) {
    var req = new XMLHttpRequest();
    req.overrideMimeType('application/json');
    req.open('GET', 'https://api.myjson.com/bins/ohp3s', true); // myjson.com url
    req.onreadystatechange = 
    function() {
        if (req.readyState == 4 && req.status == "200") {
            callback(req.responseText);
        }
    };
    req.send(null);  
}
function get(data){
    el = document.createElement(data.type);

    if(typeof el.id === 'string'){
        el.id = data.id;
    }
    if(typeof el.className === 'string'){
        el.className = data.className;
    }        
    if(typeof el.src === 'string'){
        el.src = data.src;
    }
    if(typeof el.href === 'string'){
        el.href = data.href;
    }
    if(typeof el.innerHTML === 'string'){
        el.innerHTML = data.innerHTML;
    }
    if(typeof el.alt === 'string'){
        el.alt = data.alt;
    }

    return el;
}
function recurseJSON(data){
    for(let i of data.content) {
        console.log(get(i));
        if (typeof i.content === 'object'){
           recurseJSON(i);
        }
    }
}
function initJSON() {
    loadJSON(function(res) {
        recurseJSON(JSON.parse(res));
    });
}
initJSON();
3
  • Any particular reason you're not just writing the HTML as HTML? Why the workaround with JSON and then writing your own HTML parser? It would make sense if multiple shared parts of the website came from json, but the entire page? Commented Apr 18, 2019 at 9:40
  • @gil The point is to not use jQuery Commented Apr 18, 2019 at 9:56
  • @Shilly I am just currently learning json, so my goal is to make the website with json Commented Apr 18, 2019 at 9:58

3 Answers 3

3

Append elements with the appendChild method.

document.body.appendChild(get(i));
Sign up to request clarification or add additional context in comments.

8 Comments

Based on the JSON structure, this code will not work because will append everything to the body. Children have to be added to the parent container instead of the body.
@gugateider yes, I have noticed that
@gugateider any ideas how to append each child to parent?
@Oskar — It's the same. the_element_you_want_to_append_to.appendChild(the_element_you_want_to_append)
@Quentin Yes, but how do i get the parent element, which will append the child?
|
-1

Actually both gugateider and Quentin answers make absolutely no sense. This method must be universal for any json tree. I will not answer how to solve an issue as it seems like an academic assignment. I can give you some hints how to solve your problem:

  • You would need to initialise your request on onload event
  • recurseJSON function is probably missing a parameter, which would parse parent element, which other recursion iterations would append to

BTW your could use this approach, but it needs some modification, as I guess You dont want to use any libraries.

Comments

-1

Based on your JSON structure, this is how I'd do. I just didn't load the JSON file because that's what you've done already so no problem there.

/** CODE BELOW THE DATA **/
const JSON_DATA = {
    "type": "div",
    "className": "container",
    "content": 
    [{
        "type": "header",
        "content": 
            [{
                "type": "div",
                "className": "logo",
                "content":
                [{
                    "type": "img",
                    "alt": "logo",
                    "src": "images/logo.png"
                }]
            },
            {
                "type": "div",
                "id": "reg_btn",
                "content": 
                    [{
                        "type": "span"
                    },
                    {
                        "type": "button",
                        "id": "sign_up"
                    }] 
            },
            {
                "type": "nav",
                "className": "desktop",
                "id": "menu-container",
                "content": 
                    [{
                    "type": "ul",
                    "id": "menu",
                        "content": 
                            [{
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Home"
                                }]
                            },
                            {
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Products"
                                }]
                            },
                            {
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Templates"
                                }]
                            },
                            {
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Pricing"
                                }]
                            }]
                    }]
            },
            {
                "type": "nav",
                "className": "mobile-menu",
                "content": 
                [{
                        "type": "label",
                        "innerHTML": "MENU"
                    },
                    {
                        "type": "ul",
                        "id": "mobile-menu-items",
                        "content": 
                            [{
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Home"
                                }]
                            },
                            {
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Products"
                                }]
                            },
                            {
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Templates"
                                }]
                            },
                            {
                                "type": "li",
                                "content": [{
                                    "type": "a",
                                    "href": "#",
                                    "innerHTML": "Pricing"
                                }]
                            }]
                }]
            }]
    },
    {
        "type": "section",
        "content":
        [{
            "type": "div",
            "id": "slider",
            "content":
            [{
                "type": "div",
                "id": "slider-content",
                "content":
                [{
                    "type": "article",
                    "className": "mySlides",
                    "content":
                    [{
                        "type": "span",
                        "id": "slider_title",
                        "innerHTML": "Create Stunning <br> Virtual Media"
                    },
                    {
                        "type": "p",
                        "innerHTML": "Super simple tool to create trendy videos and pictures <br> for your ads, social media, blogs and website <br> Make your project stand out!"
                    }]
                }]
            },
            {
            "type": "div",
                "id": "buttons",
                "content":
                [{
                    "type": "button",
                    "className": "slider_btn"
                },
                {
                    "type": "button",
                    "className": "slider_btn"
                },
                {
                    "type": "button",
                    "className": "slider_btn"
                },
                {
                    "type": "button",
                    "className": "slider_btn"
                }]
            },
            {
                "type": "div",
                "id": "Design_btn",
                "content":
                [{
                    "type": "button",
                    "id": "design_btn_content",
                    "innerHTML": "CREATE BUTTON &#8594"
                }]
            }]  
        }] 
    }]
};


/** CODE LOGIC STARTS HERE **/
let current = null;
const createFirstElement = (data) => {
    let el = document.createElement(data.type);
    if(typeof data.className === 'string') el.className = data.className;
    if(typeof data.id === 'string') el.id = data.id;
    if(typeof data.src === 'string') {
        el.src = data.src;
        el.alt = data.alt;
    }
        
    document.body.appendChild(el);
    current = el;

    if(typeof data.content === 'object')
        data.content.forEach((content) => createElement(content, el));

}

const createElement = (data, parent) => {

    let el = document.createElement(data.type);

    if(typeof data.className === 'string') el.className = data.className;
    if(typeof data.id === 'string') el.id = data.id;
    if(typeof data.src === 'string') {
        el.src = data.src;
        el.alt = data.alt;
    }
    if(parent !== undefined) parent.appendChild(el);
    else current.appendChild(el);

    if(typeof data.content === 'object') {
        //current = el;
        data.content.forEach( (content) => createElement(content, el) );
    } else {       
        if( typeof data.innerHTML === 'string' ) el.innerHTML = data.innerHTML;
    }

}

// loopData(JSON_DATA);
createFirstElement(JSON_DATA);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.