String building attribute selectors I'm dynamically selecting elements in jQuery, how can I make it more resilient?

$('[data-example="' + exampleData + '"]').each(...);


I'm concerned that the data might contain special characters.
Avoid string building jQuery selectors. If your exampleData variable might contain special characters, or possibly contains user input, you've opened yourself to selector injection.

For example, if exampleData has a value of:

'"],body,[a="'


The computed selector becomes:

[data-example=""],body,[a=""]


which might cause unexpected behavior.

More typically, the selector will just fail outright, and your page or app will not work as expected.



Although jQuery calls itself the "write less, do more" library, this is a case where you'll need to write a bit more.

Instead of string building a single selector, use .filter():

$('[data-example]').filter(function () {
  return $(this).data('example') === exampleData;
});