Cannot set property X of undefined - programatically created element

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2012-06-12T10:26:48Z Indexed on 2012/06/12 10:40 UTC
Read the original article Hit count: 272

Filed under:

I am working on a class to create a fairly complex custom element. I want to be able to define element attributes (mainly CSS) as I am creating the elements. I came up with the below function to quickly set attrs for me given an input array:

// Sample array structure of apply_settings
//var _button_div =   {
//    syle    :   {
//        position:   'absolute',
//        padding :   '2px',
//        right   :   0,
//        top     :   0
//    }
//};
function __apply_settings(__el,apply_settings){
    try{
        for(settingKey in apply_settings){
            __setting = apply_settings[settingKey];
            if(typeof(__setting)=='string'){
                __el[settingKey] = __setting;
            }else{
                for(i in __setting){
                    __el[settingKey][i] = apply_settings[settingKey][i];
                } 
            }
        }
    }catch(ex){
        alert(ex + "   " + __el);
    }
}

The function works fine except here:

function __draw_top(){
    var containerDiv = document.createElement('div');
    var buttonDiv = document.createElement('div');
    __apply_settings(containerDiv,this.settings.top_bar);
    if(global_settings.show_x)
        buttonDiv.appendChild(__create_img(global_settings.images.close));
    containerDiv.appendChild(buttonDiv);
    __apply_settings(buttonDiv,this.settings.button_div);
    return containerDiv;
}

The specific section that is failing is __apply_settings(buttonDiv,this.settings.button_div); with the error "Cannot set property 'position' of undefined". So naturally, I am assuming that buttonDiv is undefined.. I put alert(ex + " " + __el); in __apply_settings() to verify what I was working with. Surprisingly enough, the element is a div. Is there any reason why this function would be working for containerDiv and not buttonDiv? Any help would be greatly appreciated :)

{EDIT} http://jsfiddle.net/Us8Zw/2/

© Stack Overflow or respective owner

Related posts about JavaScript