2
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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;
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.