I have an array of sports items. I am trying to build an array of category names from the main array. Each category name is then created as a hyperlink element which onclick triggers a function that loads the associated products. I also need to display one instance of the category name as there are multiple.
When I click the button and call filterCategory(), nothing is getting displayed. The error I am getting in Chrome Developer Tools is when I call:
document.getElementById("brand-category").appendChild(categoriesLink);
... the error on this line is:
failed to execute appendChild on 'Node': paramater 1 is not type Node
Here is what I have tried so far:
var data = {
"Nike": [
{
"id": "1",
"brand":"Nike",
"productTitle": "Black Hoody",
"productImage": "image.jpg",
"category": "Hoodies",
"priceBand": "1103",
"salePrice": "120.00"},
{
"id": "2",
"brand":"Nike",
"productTitle": "Running Jacket",
"productImage": "image.jpg",
"category": "Jackets",
"priceBand": "1104",
"salePrice": "150.00"}
],
"Sketchers": [
{
"id": "3",
"brand":"Sketchers",
"productTitle": "Running Shoes Style 1",
"productImage": "image.jpg",
"category": "Running Shoes",
"priceBand": "1103",
"salePrice": "120.00"},
{
"id": "4",
"brand":"Sketchers",
"productTitle": "Running Shoes Style 2",
"productImage": "image.jpg",
"category": "Running Shoes",
"priceBand": "1102",
"salePrice": "90.00"}
]}
function filterCategory() {
//build an array of unique category names from the main array.
//create an element and assign the category name as a link
//on click, load the associated products from that category
var categories, categoriesLink;
for(categories in data) {
categoriesLink = document.createElement("a");
categoriesLink.innerHTML = categories;
categoriesLink.categories_Arr=data[categories];
categoriesLink = function() {
var catsContainer=document.getElementById('brand-category');
var categories_Arr=this.categories_Arr, i, I=categories_Arr.length, item;
var catOutput="";
for(i=0; i<I; I++)
{
item=categories_Arr[i];
catOutput+= "<img src=\""+item.logo+"\"/>" + item.id + item.productTitle + item.productDescription + "<img src=\""+item.productImage+"\"/>" + item.rrp + item.salePrice + "<br>";
}
catsContainer.innerHTML=catOutput;
catsContainer.style.display="block";
return false;
}
document.getElementById("brand-category").appendChild(categoriesLink);
}
}
<div id='cat'><button id='filterCategory' name='filterCategory' value='Category' onclick="filterCategory();">Category</button></div>
<div id="brand-category"></div>
Any help much appreciated.
Cheers
categoriesLinkwith a function, probably you meant to assign it as an eventhandler?categoriesLink.