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();
1

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

6 Comments

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 .
@RanaGhosh true, I took the OP to mean 'that data attribute' as including the value. I'll update to cover both scenarios. Thanks
How would the Syntax look like if I do this $("div[id='foo']").
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]')
I think that will be $("div#foo[data-type]")this .
|
1
if(typeof $("#foo").attr('data-type') == 'undefined')
{
  $("#foo").removeAttr('data-type');
}

Comments

0

If you dont care about the value you can just do

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.