Alexandre
Alexandre

Reputation: 759

Select object by data attribute

How to select a object by data? I've found many examples but none of them seens work for me:

$('div').data('name', 'foo');

I've tried:

$('div').find('[data-name]="foo"').hide();
$('div[data-name]="foo"').hide();
$('div[name]="foo"').hide();

any idea?

Upvotes: 0

Views: 96

Answers (3)

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14302

Try this instead

$('div[data-name=foo]').hide()

Hope this will help !!

Upvotes: 2

Geo
Geo

Reputation: 13016

Use .attr instead:

$('div').attr('data-name', 'foo');
$('div[data-name="foo"]').hide();

This article might be interesting to take a look at.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337691

Try filter():

var $div = $('div').filter(function() {
    return $(this).data('name') === 'foo'; 
});
$div.hide();

Upvotes: 2

Related Questions