1

I would like to find all elements inside a container that have a certain data attribute set to 1 as well as all elements that don't have this attribute set at all.

The data attribute is as follows:

$("#element").data("activate")

It can have a value of 1 or 0. If an element doesn't have an "activate" data property set I want to treat it as a 0.

I have the following code at present:

$("#content").find("[data-activate='0']").off();

However I would also like to do something like this:

$("#content").find("all where data-activate NOT exists").off();

ie if an element doesn't have the attribute even set.

1
  • Note: there must be unique ID for any element on a page. Commented Jan 7, 2013 at 12:44

4 Answers 4

3

You can use :not:

$('#content :not([data-activate])').off();

Or filter():

$('#content div').filter(function() {
    return !$(this).attr('data-activate');
}).off();
Sign up to request clarification or add additional context in comments.

3 Comments

This is a great answer if your selector identifies the nodes already. If you're using find it means you're looking for descendants of #content, so use whichever one is appropriate as the situation comes up.
@Plynx I don't get what you mean - the selector in the first example will find descendants of #content
I caught you between earlier edits, your answer finds descendants now.
3
$("#content").find(":not([data-activate])").off();

1 Comment

@Tomalak I think that would apply filter away any #content without this attribute, not its descendants. Since #content is an id, JQuery takes a shortcut and only returns the first even if you have multiples with that ID.
0

TRY

$("#content div").map(function {
    $(this).data("activate","1") 
}

This will simply add data-activate = 1 to all div inside #content whether it is 0 or that attribute does not exist

Comments

0

You can use the two selector at once to select the element, separting them (selectors) by comma

  1. :not() Selector.
  2. Attribute Equals Selector.

    $("#content [data-activate='0'], #content :not([data-activate])").off();

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.