Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Check if a container div has a child with a specified attribute value

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.

like image 935
jgille07 Avatar asked Jan 26 '13 05:01

jgille07


2 Answers

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.

like image 184
undefined Avatar answered Nov 02 '22 08:11

undefined


How about the find() method?

var $children = $('.container').find('.child[myattr="myattrvalue3"]');

And to find the number of children:

$children.length
like image 41
thordarson Avatar answered Nov 02 '22 06:11

thordarson