2

How can I check if a div has a data-attribute and remove the div if it has that data-attribute, the opposite works like this:

$("div[id='foo']").not('[data-type=edit]').remove();
Micheasl
  • 277
  • 1
  • 5
  • 25
  • Possible duplicate of [Select elements by attribute](http://stackoverflow.com/questions/1097522/select-elements-by-attribute) – Connagh Jacobi Mar 24 '17 at 11:58

3 Answers3

5

Remove the not() and use the attribute in the main selector:

$('#foo[data-type=edit]').remove();

If you only want to find the element that has the data-type attribute, regardless of its value, you can use this:

$('#foo[data-type]').remove();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • This might be wrong because he is asking about `data-type` is present or not. That means `data-type` might have any value. Your code only works only if `data-type=edit` . – Rana Ghosh Mar 24 '17 at 12:00
  • 1
    @RanaGhosh true, I took the OP to mean 'that data attribute' as including the value. I'll update to cover both scenarios. Thanks – Rory McCrossan Mar 24 '17 at 12:01
  • How would the Syntax look like if I do this `$("div[id='foo']").` – Micheasl Mar 24 '17 at 12:02
  • 1
    That syntax is pretty redundant. The only reason you'd need to use it is if you have multiple elements with the same `id`, which you really, really shouldn't. To answer your question though, you can use multiple attribute selectors like this: `$('div[id="foo"][data-type]')` – Rory McCrossan Mar 24 '17 at 12:03
  • 1
    I think that will be `$("div#foo[data-type]")`this . – Rana Ghosh Mar 24 '17 at 12:04
  • ok Thanks alot have a nice day and a nice Weekend :D (Ill accept in a few minutes) – Micheasl Mar 24 '17 at 12:04
1
if(typeof $("#foo").attr('data-type') == 'undefined')
{
  $("#foo").removeAttr('data-type');
}
Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40
0

If you dont care about the value you can just do

$('#foo[data-type]').remove();
MaanooAk
  • 2,418
  • 17
  • 28