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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With