简体   繁体   中英

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

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 (eg, 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>

You can also use a filter function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM