Fly
Fly

Reputation: 862

HTML-modifying JavaScript Code says that my HTML Element is undefined

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?

Upvotes: 0

Views: 163

Answers (1)

Fly
Fly

Reputation: 862

The problem was that the ownedBy variable of Category was set to the name of the super-category, instead of its ID (In another part of the code which I thought was irrelevant)

Upvotes: 3

Related Questions