Jquery and adding row to table

jquery

I have the following jquery code.

var destTable = $("#numbers");
$(document).ready(function() {
  $("#btnAdd").click(function() {
   //Take the text, and also the ddl value and insert as table row.
   var newRow = $("<tr><td>hi</td></tr>");
   $("#numbers").append(newRow);
  });
});

What I would really like is to store a reference to an element once and then use it from there on it.

The code above add's a row to my table as expected but if I use. $(destTable).append(newRow) or destTable.append(newRow) nothing happens could anyone shed any light on this for me?

Thanks

Best Solution

Keep the reference inside document.ready:

$(document).ready(function() {
  var destTable = $("#numbers");
  $("#btnAdd").click(function() {
   //Take the text, and also the ddl value and insert as table row.
   var newRow = $("<tr><td>hi</td></tr>");
   $("#numbers").append(newRow);
  });
});

The point of document.ready is to wait for the DOM to be ready; if you try doing $('#numbers'); outside of it (and the code does not appear after the element in the document) the DOM will not have yet created this element so you won't have a proper reference to it.

Once you do this, you should be able to do:

destTable.append(newRow);

Inside the click function. As a last note, however, it is a common and accepted practice to preface variables that represent jQuery sets with a $. So this is best:

var $destTable = $("#numbers");