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

JquerySyntaxSelect

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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);

Solution 2 - Jquery

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

Solution 3 - Jquery

Doing $('body').find(); is not necessary when looking up by ID; there is no performance gain.

Please also note that having an ID that starts with a number is not valid HTML:

>ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Solution 4 - Jquery

You can do it like this:

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

Solution 5 - Jquery

There are two problems with your code

  1. To find an element by ID you must prefix it with a "#"
  2. You are attempting to pass a Number to the find function when a String is required (passing "#" + 5 would fix this as it would convert the 5 to a "5" first)

Solution 6 - Jquery

I don't know much about jQuery, but try this:

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

Edit: Of course, if the variable is a number, you have to add "#" to the front:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTonyView Question on Stackoverflow
Solution 1 - JqueryRick HochstetlerView Answer on Stackoverflow
Solution 2 - JqueryJohn RaschView Answer on Stackoverflow
Solution 3 - JqueryPaolo BergantinoView Answer on Stackoverflow
Solution 4 - JqueryAmr ElgarhyView Answer on Stackoverflow
Solution 5 - JqueryBert LambView Answer on Stackoverflow
Solution 6 - JqueryZifreView Answer on Stackoverflow