Search code examples
javascriptfunctionobjectappendchild

javascript: unknown-why undefined variables


The following code is to make a lever move back and forth and change the color of a square. However, the following is the bare bones of the elements involved where I am stuck. The error IE gives me is "value of the property 'appendChild': object is null or undefined" This is located at the XXXXX's in the code. Also, I was getting confused when to use " " and when to us ' ' when I wrote this code. It runs fine until the XXXX's where I get an error.

  function sliderBox(style){ 
     this.style = style;
     var line = null;
     var bar = null;
     var divElem1 = document.createElement('div');
     this.divElem = divElem1.setAttribute('class', 'sliderBox');

    this.constructDOM = function(){ 
     line = new sliderLine();
     bar = new sliderBar(style);
     var ldE = line.divElem;  
     ldE.appendChild(bar.divElem);  XXXXXX PROBLEM HERE
     var tdE = this.divElem;
     tdE.appendChild(line.divElem);
   }    


 }

  function sliderLine(){
    var divElem1 = document.createElement('div');
    this.divElem = divElem1.setAttribute("class", "sliderLine");
  }

  function sliderBar(style){
    this.style = style;
    var divElem1 = document.createElement('div');
    var sBs = "sliderBar" + style;
    this.divElem = divElem1.setAttribute('class', sBs);
  }

Anybody know?


Solution

  • You are assiging divElem to the return value of setAttribute in the last line of your code. The return value of setAttribute is null or undefined [1]. When you try to appendChild in the line marked with XXXX this gives an error. You should change you sliderBar function to

    function sliderBar(style){
       this.style = style;
       var divElem1 = document.createElement('div');
       var sBs = "sliderBar" + style;
       divElem1.setAttribute('class', sBs);
       this.divElem = divElem1;
    }
    

    [1] http://reference.sitepoint.com/javascript/Element/setAttribute