Danil Pyatnitsev
Danil Pyatnitsev

Reputation: 2292

How to select all elements by data-attribute with specific value using jQuery

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

Upvotes: 1

Views: 322

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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>

Upvotes: 2

i.signori
i.signori

Reputation: 595

You can also use a filter function

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

Upvotes: 0

Related Questions