Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 651
Tony Avatar asked Apr 13 '09 14:04

Tony


People also ask

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do you select an element with ID data '?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

Can you use a variable in a jQuery selector?

Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.

How do I select something in jQuery?

The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector). select(function);


2 Answers

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); 
like image 199
Rick Hochstetler Avatar answered Sep 30 '22 05:09

Rick Hochstetler


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.

like image 37
John Rasch Avatar answered Sep 30 '22 03:09

John Rasch