0

I have this script

var b = {
  c: {
    a: document.querySelector(".a"),
    init: function() {
      this.a.style.backgroundColor = "red";
      this.a.addEventListener("click", b.c.change);
    },
    change: function() {
      this.a.style.width = "100px";
    }
  }
}
b.c.init();
.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
<div class="a"></div>

Why this.a style "undefine"???

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40

3 Answers3

1

Inside the change event handler, this refers to the dom element. So just change this.a.style.... to this.style.... .

var b = {
  c: {
    a: document.querySelector(".a"),
    init: function(){
      this.a.style.backgroundColor="red";
      this.a.addEventListener("click", b.c.change);
    },
    change: function(){
      this.style.width="100px";
    }
  }
}
b.c.init();
.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
<div class="a"></div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

First, in change event, this is pointing to DOM element and not object. So you can directly update style using this.

Second, inside a, this will point to c, so instead of b.c.change, you can directly do this.change

var b = {
  c: {
    a: document.querySelectorAll(".a"),
    init: function() {
      for (var i = 0; i < this.a.length; i++) {
        this.a[i].style.backgroundColor = "red";
        this.a[i].addEventListener("click", this.change);
      }
    },
    change: function() {
      console.log(this.innerHTML)
      this.style.width = "100px";
    }
  }
}
b.c.init();
.a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
  margin: 5px;
  padding: 5px;
}
<div class="a">1</div>
<div class="a">2</div>
<div class="a">3</div>
<div class="a">4</div>
<div class="a">5</div>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
-4

Try once this will work..

var b = {
  c: {
    a: document.getElementById("a"),
    init: function(){
      this.a.style.backgroundColor="red";
      this.a.addEventListener("click", b.c.change);
    },
    change: function(){
      this.style.width="100px";
    }
  }
}
b.c.init();
#a {
  width: 10px;
  height: 10px;
  background: black;
  cursor: pointer;
}
<div id="a"></div>
BEJGAM SHIVA PRASAD
  • 2,181
  • 1
  • 18
  • 27