简体   繁体   中英

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! :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM