Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom data-attribute selector not working

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?

like image 619
matt Avatar asked Jan 18 '26 03:01

matt


1 Answers

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.

like image 144
zzzzBov Avatar answered Jan 19 '26 18:01

zzzzBov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!