Aaron
Aaron

Reputation: 3245

Using data attributes and jQuery how can I select elements by data attribute name AND data attribute value

I need to select elements by data attribute name AND data attribute value.

Something like (but obviously, it doesn't work)

for(var i=0; i<x.length; i++){
    var y = $('.my-class').attr('data-id', i); //trying to select here
    y.html('input' + i);                                
}

Have no idea how to achieve this, please help! :)

Upvotes: 1

Views: 233

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

you can use attribute selector

var y = $('.my-class[data-id="' + i + '"]');

since the selector .my-class is repeated, you can cache it

var els = $('.my-class');
for(var i=0; i<x.length; i++){
    var y = els.filter('[data-id="' + i + '"]'); //trying to select here
    y.html('input' + i);                                
}

Demo: Fiddle

Upvotes: 1

Related Questions