'I am trying to modify data from a JSON file and put it into an HTML file. How do I fix my code so that it works?

var obj = JSON.parse(portfolioData.json);

function appendData(data) {

    var code = "";

    for (var i = 0; i < data.length; i++) {

        var current = data[i];

        code = code + '<div class="post flexbox"> <div class="column20 ver-center" style="margin-right: 30px;">';
        code = code + '<h6>' + current.date[0] + '<br>' + current.date[1] + '<br>' + current.date[2] + '</h6></div>';
        code = code + '<div class="column80 ver-center">';
        code = code + '<a href="' + current.link + '" target="_blank">';
        code = code + '<h2 class="white"><u>' + current.title + '</u></h2></a>';
        code = code + '<p>' + current.description + '</p></div></div>';

    }

    return code;

}

document.getElementById("main-portfolio").innerHTML = appendData(obj);

All the code above is within tags inside the div with the tag "main-portfolio". When I open the HTML file as normal, the data from the JSON does not show up in the HTML file. How do I fix this problem?

The json file "portfolioData.json" is in the same directory as the main HTML file. The format of the JSON is below.

[
    {
        "title": "SAMPLE TITLE",
        "link": "https://google.com",
        "date": ["22", "11", "20"],
        "description": "SAMPLE DESCRIPTION"
    }

]


Solution 1:[1]

you said: All the code above is within tags inside the div with the tag "main-portfolio"

this implies that the script you wrote is trying to run before the #main-portfolio element has been added to the document object model.

maybe try running the script later on in the page.

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 Kae Verens