Is there an alternative to building selector strings in jquery?
In particular, I am trying to extract information from the labels of several form elements, so I need to create queries like $('[for=#id]'). It seems inelegant (and probably inefficient) to have to create the query strings on every pass of every iteration over the form elements.
The only similar question I can find is jQuery (anti-)pattern: building selectors with string manipulation which doesn’t have any useful answers.
At-least limit the search to the form in which you are looking. Searching by attributes is in-efficient because you have to iterate over every element in the root set of elements. so instead of searching every element in the DOM, limit your search:
You can make this a bit faster by searching for labels inside the form, then filtering down to just what you want:
If your labels don’t change dynamically then you should cache their selection outside of your loop; always cache values that do not change within the loop, outside of the loop.