2

I'm trying to select element by data attribute defined with jquery (it's not visible in DOM), therefore I cannot use $('.foo:data(id)')

example: if user clicks element I add data property to it as following

$(this).data('id', '1');

now I would like to find element which has data-id == 1

how can I select this element by data-id?

Lukáš Václavek
  • 442
  • 1
  • 6
  • 12
  • `$('.foo').filter(function(){ $(this).data('id') == 1; })` – Satpal Nov 12 '18 at 11:49
  • @Wimanicesir The question you linked is selecting by data attribute defined in DOM, I'm dealing with data defined in jQuery. – Lukáš Václavek Nov 12 '18 at 11:50
  • @Satpal - the linked question isn't reflecting, that the data attribute isn't present in the dom, so this isn't a duplicate for the linked quesiton – Philipp Nov 12 '18 at 11:54
  • @Philipp, There is couple of answer which clearly suggest `.filter()` i.e. https://stackoverflow.com/a/41061135 thus I believe its a duplicate and also I didn't answered it although tried to nudge OP in correct direction via comment – Satpal Nov 12 '18 at 11:56
  • @Satpal That's true, but the question isn't about that, as you can see in the first 9 answers – Philipp Nov 12 '18 at 11:59
  • @Philipp, Be happy revoked my dupe hammer – Satpal Nov 12 '18 at 12:00
  • @Satpal https://stackoverflow.com/questions/2891452/jquery-data-selector – Philipp Nov 12 '18 at 12:00
  • Possible duplicate of [jquery data selector](https://stackoverflow.com/questions/2891452/jquery-data-selector) – cнŝdk Nov 12 '18 at 12:36

2 Answers2

1

You could use the attribute selector [attribute=...].

In your case, this would be

$('[data-id=1]')

But keep in mind, if you change the data of an element with .data(), the change isn't reflected in the dom attribute, so you can't use this (or additionally change the dom attribute).

The other way would be to select every candidate and then filter for each element, which has a matching data value.

$('.foo').filter(function(){
    return $(this).data('id') == 1;
});
Philipp
  • 15,377
  • 4
  • 35
  • 52
1

Use filter()

$('.foo').filter(function(){
    return $(this).data('id') === `1`
}).doSomething()
charlietfl
  • 170,828
  • 13
  • 121
  • 150