10

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

2 Answers 2

22

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense when I thought about it cheers for that worked a treat.
0

Your can use appendTo like this :

$("<tr><td>Hello</td><tr>").appendTo("#MyTable > tbody") 

2 Comments

Should that not be <tr><td>Hello</td></tr> ?
@MadMaardigan YES! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.