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.

asked Jul 8, 2016 at 14:39
\$\endgroup\$

1 Answer 1

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;
});
answered Jul 8, 2016 at 14:39
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.