2

Any idea why this happens …

    var attr = $(this).data('link');
    console.log(attr); // profile_following
    console.log($("a[data-target='profile_following']")); // found the object
    console.log($("a[data-target='+attr+']")); // [] empty

Inside of a click handler I have the lines above! console.log(attr); successfully prints profile_following However if I try to select a link with an attribute selector and this variable like this console.log($("a[data-target='+attr+']")); it can't find the element!

And the weirdest thing after all is if I hardcode the line like that console.log($("a[data-target='profile_following']")); it finds the object successfully.

Any idea why the same line wouldn't work with the +attr+ inside the attribute selector?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
matt
  • 42,713
  • 103
  • 264
  • 397
  • You have to inject `attr` into the selector, so you have to delimit the prefix and suffix strings with double quotes (`"a[data-target='" + attr + "']"`). Also, this is a duplicate of [jQuery how to find an element based on a data-attribute value?](http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value) – Frédéric Hamidi Feb 14 '12 at 18:26

1 Answers1

13

You need to use string concatenation to create a string with a value of "a[data-target='profile_following']". You do that with:

$('a[data-target="'+attr+'"]');

In your example, +attr+ is part of the string because you never closed and reopened your quotes.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367