4

How can I find all elements without a certain data-attribute?

I've tried:

$list.find('li:not([data-stuff])');

But it doesn't work.

3
  • what is $list element, can you share the html as well Commented Nov 11, 2013 at 15:59
  • is the data attribute modified by script or is it present in the html markup Commented Nov 11, 2013 at 16:01
  • data is added by script Commented Nov 11, 2013 at 16:01

2 Answers 2

6

jQuery stores data attributes in its cache, so you need to use filter:

var $li = $list.filter(function() {
    return $(this).data('stuff') != undefined;
});
// do something with $li...
Sign up to request clarification or add additional context in comments.

2 Comments

you may have to check whether data('suff')!=undefined else falsy values like false and 0 will fail
@Vic If there was a selector to do exactly what you wanted, it would probably just do something similar to this internally anyway. But you could use something like this if you really wanted to do it in a selector. Hell, even build your own :)
5

I think what you're looking for is:

$list.find('li').not('li[data-stuff]').addClass('foo');

The addClass() is just there as a placeholder.

2 Comments

Notice in that codepen how it only logs text for the two items that don't have a [data-stuff] attr. I assume you're looping through items or something in your code...
It doesn't seem to work when you add the data via javascript instead of html. codepen.io/anon/pen/doyfj

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.