I want to be able to check if a container div has a child in it with an attribute of a particular value and also how many instances exist.
For example, if I had the following HTML:
<div class='container'>
<div class='child' myattr='myattrvalue1'>DIV CONTENTS</div>
<div class='child' myattr='myattrvalue2'>DIV CONTENTS</div>
<div class='child' myattr='myattrvalue3'>DIV CONTENTS</div>
<div class='child' myattr='myattrvalue3'>DIV CONTENTS</div>
<div class='child' myattr='myattrvalue3'>DIV CONTENTS</div>
<div class='child' myattr='myattrvalue4'>DIV CONTENTS</div>
</div>
I would like a jquery line that that would be able to find if any div with class "child" in $(".container") has an attr of "myattr" and a value of "myattrvalue3". I would also like to be able to determine how many instances of such a child exists, which would be 3 instances of the child with myattr='myattrvalue3' in this example.
var $elems = $('.container .child[myattr=myattrvalue3]');
var length = $elems.length; // length of the selected elements
Note that myattr
is not a valid attribute. You can use HTML5 data-*
attributes instead.
How about the find() method?
var $children = $('.container').find('.child[myattr="myattrvalue3"]');
And to find the number of children:
$children.length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With