How do I select an element in jQuery by using a variable for the ID?

Tony picture Tony · Apr 13, 2009 · Viewed 213.3k times · Source

For example, the following selects a division with id="2":

row = $("body").find("#2");

How do I do something like this:

row_id = 5;
row = $("body").find(row_id);

The above syntax produces an error. I checked the jQuery documentation and answers here without success.

Answer

Rick Hochstetler picture Rick Hochstetler · Apr 13, 2009
row = $("body").find('#' + row_id);

More importantly doing the additional body.find has no impact on performance. The proper way to do this is simply:

row = $('#' + row_id);