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.
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.
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.
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.
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);
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);
The shortest way would be:
$("#" + row_id)
Limiting the search to the body doesn't have any benefit.
Also, you should consider renaming your id
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With