I'm currently trying to get a simple Category System to work. To do so, I've created a tiny Category "class" which fits my needs:
var categories = [];
function Category (id, name, ownedBy){
this.id = id;
this.name = name;
this.ownedBy = ownedBy;
categories[id] = this;
}
id is, well, the ID of the Category. It's name is only used for display purposed. And "ownedBy" is the ID of the super-category, or "none" if it hasn't one.
After filling my categories-array, I iterate over it and call a function of mine to add the categories to my HTML-Code:
function addHTMLCategory(catID){
var cat = categories[catID]; //Get the Category-"Object"
if(!cat) return; //If it doesn't exist, do nothing.
if(cat.ownedBy != "none"){ //If the category has a supercategory,
addHTMLCategory(cat.ownedBy); //Add it to the HTML first.
}
if(document.getElementById("cat"+catID)) return; //And if it already exists, dont add it again.
//ERROR-PART: If a category has a superclass, get the superclass element.
var contentElement = document.getElementById(cat.ownedBy=="none"?"categories":"cat"+cat.ownedBy);
var li = document.createElement("div");
li.id = "cat"+catID;
li.className = "category";
li.innerText = cat.name;
contentElement.appendChild(li);
}
Initial HTML:
<div id="categories"></div>
This function checks if the Category has a Super-Category, and if yes, it adds this one first: I did this to avoid that the element where the category should be added to doesn't exist.
Unfortunately, exactly this happens: When a Category has a super-category, the "contentElement" variable is null. Could anyone tell me why?
li ...element creation...code, as well as your initial HTML, and your sequence of add events. As John Smith pointed out, something isn't existing in your DOM but we don't see how your DOM starts or how it is set. or make a fiddle/add a code widget?console.log(cat.ownedBy)will bring some lightcat.ownedByis not a valid index into categories, the recursion will obtain undefined forcategories[catId]and simply return. BTW, you make sure catId is a number if not "none".