Yuriy
Yuriy

Reputation: 83

Select an element by data attribute using jquery

Is there a way to select element by its data attribute using jQuery? I have a div

<div class="remove">delete</div>

And I've added data attributes to it like so:

$('.remove').attr('data-id', data._id);
$('.remove').attr('data-rev', data._rev);

What I want is to select this element based on its 'data-id' and 'data-rev' using jQuery.

Thanks!

Upvotes: 2

Views: 161

Answers (5)

GautamD31
GautamD31

Reputation: 28763

Try like

$('.remove[data-id = "' + data._id + '"]');
$('.remove[data-rev = "' + data._rev + '"]');

If you want to check both the data then you can use

$('.remove[data-id = "' + data._id + '"][data-rev = "' + data._rev + '"]');

Upvotes: 2

codingrose
codingrose

Reputation: 15699

Try:

$('.remove[data-id = "' + data_id + '"][data-rev = "' + data_rev + '"]');

Upvotes: 2

palaѕн
palaѕн

Reputation: 73886

You can do this using .filter():

var $dataId = $('.remove').filter(function(){
    return $(this).data('id') === 'something';
});

var $dataRev = $('.remove').filter(function(){
    return $(this).data('rev') === 'something';
});

and then you can use the variables like:

$dataId.show();
$dataRev.hide();

Upvotes: 1

Try attribute-equals-selector

$('.remove[data-id="'+data._id+'"]')
$('.remove[data-rev="'+data._rev+'"]');

Upvotes: 1

Rituraj ratan
Rituraj ratan

Reputation: 10378

$('.remove[data-id="'+data._id+'"]');
$('.remove[data-rev="'+data._rev+'"]');

reference attribute-equals-selector

Upvotes: 1

Related Questions