matt
matt

Reputation: 44303

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?

Upvotes: 2

Views: 10632

Answers (1)

zzzzBov
zzzzBov

Reputation: 179086

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.

Upvotes: 13

Related Questions