0

I need to append to a DOM object - but I don't know in advance which object that will be (depends what the user selects in the UI). So I must generate the id dynamically and then append - but I'm struggling to find a way to do this.

For example, to append to a table with an id of my-table-13 I'd like to do something like this:

var $Table = 'my-table-' + value;

$(Table)
    .append($("<tr>")
        .attr('id','my-row'));

I've tried variations of inserting brackets and #'s on the first line - but no success. Is this possible?

1
  • 3
    If your variable is $Table then the jQuery would start with $($Table), not $(Table). Commented Aug 9, 2013 at 16:42

2 Answers 2

1
var table = '#my-table-' + value; // or '.my-table-'

and then

$(table).....

$Table is a valid variable name in javascript, so $Table and Table used in $(Table) are different. You were actually trying to use $(undefined)...

Using something like $($Table) works but it's considered bad syntax.

Sign up to request clarification or add additional context in comments.

2 Comments

if the table variable is the id make sure to add '#' to the selector as well. '#my-table-' + value
Both answers show valid solutions which I'm grateful for - giving this the vote for the slightly greater detail.
0

You need a # to grab an ID, also reference $Table not Table

var $Table = 'my-table-' + value;

$("#" + $Table)
    .append($("<tr>")
        .attr('id','my-row'));

Comments

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.