I have a JSON file named colors.js and looks like this:
{
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
]
}
Here is how I have handled the html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type="primary" src="colors.json"></script>
<script type="text/javascript">
colorItems=['beige', 'red', 'blue'];
function loadJSON() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'colors.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
colorItems.push(JSON.parse(xobj.responseText)); // line 21
console.log(xobj.responseText); // line 22
}
};
}
function loadData(){
for (i=0; i<4; i++){
console.log(colorItems[i]);
document.getElementById('myP1').innerHTML+=colorItems[i]+'<br>';
}
}
</script>
<title></title>
</head>
<body onload="loadData()">
<p class="myP" id="myP1"></p>
<p class="myP" id="myP2"></p>
<p class="myP" id="myP3"></p>
<p class="myP" id="myP4"></p>
<p class="myP" id="myP5"></p>
</body>
</html>
I need when the page loads, information from each object (in the JSON file) be pushed to colorItems
array. Then, they array renders to the paragraphs (that have class myP
) in the body. However, I face two problems:
- I am only able to get data to the paragraphs using
getElementById
, but notgetElementsByClassName
. - I am not able to get the right data be pushed into
colorItems
array. Consequently, I am not able to get needed info on the html page.
This is how the output looks like (and how I need it to be):