1

I have a truble with jQuery. How to write a selector that selects only elements, witch have an data-attribute and specific value.

I'm trying:

$('form').find('*[data-root!=0]')

it's returns all elements - with/without data-root.

$('form').find('*[data-root]').find('*[data-root!="0"]')

and this code return nothing

1
  • Post an HTML sample please Commented Nov 12, 2019 at 16:36

2 Answers 2

2

Remove the *. There's also no need for find. You need to add [data-root] on its own. This finds all descendant elements of form elements that have data-root with a value that isn't 0:

$('form [data-root][data-root!=0]')

although I think I'd be more comfortable putting the 0 in quotes:

$('form [data-root][data-root!="0"]')

That's because 0 isn't a valid CSS identifier, and the value of an attribute must be a valid CSS identifier or a string (e.g., in quotes) (more here).

Selector explanation:

form [data-root][data-root!="0"]
/^^\^/^^^^^^^^^\/^^^^^^^^^^^^^^\
 |  |     |            |
 |  |     |            +−−− the attribute can't be equal to "0"
 |  |     +−−−−−−−−−−−−−−−− must have the attribute
 |  +−−−−−−−−−−−−−−−−−−−−−− is a descendant...
 +−−−−−−−−−−−−−−−−−−−−−−−−− ...of a `form`

Live Example:

$('form [data-root][data-root!="0"]').each(function(i) {
    console.log(i + ": " + $(this).text());
});
<form>
  <div data-root="0">no match (value is 0)</div>
  <div>no match (no attribute)</div>
  <div data-root="1">match (value is "1")</div>
</form>
<form>
  <div data-root="0">no match again (value is 0)</div>
  <div>no match again (no attribute)</div>
  <div data-root="">match (value is "")</div>
  <div data-root="2">match (value is "2")</div>
</form>
<div data-root="3">no match (not in a <code>form</code>)</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

@DanilPyatnitsev - Ah! Silly me. Fixed. Adding [data-root] tells the selector engine we only want ones that have the attribute. Combined with [data-root!="0"], we get only the ones that have it, but don't have it with the value "0".
0

You can also use a filter function

$('form').find('[data-root]').filter("[data-root!='0']");

1 Comment

Fairly inefficient given that filtering is what CSS selectors do, but yes, it's possible. (And it's not often that the efficiency matters.)

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.