user736893
user736893

Reputation:

Storing a JQuery selected element as a JavaScript object property?

This is hopefully something very simple I am overlooking, but I am simply trying to store a JQuery reference as a property so I can reuse it more easily.

var debug = {
  pane: $('#debugOutput'),
  show: function() {
    debug.pane.show();
    console.log(debug.pane.length);  //0
    console.log($('#debugOutput').length);  //1
  }
}

The .show() does not work. The element is never made visible. In the Chrome console, this is what debug.pane looks like:

enter image description here

And, of course, the actual JQuery object:

enter image description here

Upvotes: 0

Views: 25

Answers (1)

Luca Kiebel
Luca Kiebel

Reputation: 10096

You should use this instead of debug:

let debug = {
  pane: $('#debugOutput'),
  show: function() {
    this.pane.show();
    console.log(this.pane.length);  //1
    console.log($('#debugOutput').length);  //1
  }
}

debug.show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/300" style="display:none" id="debugOutput">

You can't reference debug in itself, since the statement defining it hasn't finished yet.

Upvotes: 3

Related Questions