user2881780
user2881780

Reputation: 23

Jquery:How to use variable as a selector

I trying to figure out how can I use a variable inside a selector. If I use the actual value of the ID in the selector, it works very well.

$(document).on("click",'.tag', function(){
    var data-id = $(this).attr('data-id');

    if($('div[data-id="540"]').hasClass("tag_current")) {
        $('div[data-id="540"]').removeClass("tag_current").addClass("tag");
    }
    $(this).toggleClass('tag tag_current');
});

I checked many answers and try it in different ways, but I still didn't solve it.

Upvotes: 2

Views: 145

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Basic string concatenation:

$('div[data-id=' + data-id + ']')

Upvotes: 2

Related Questions