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

jgille07 picture jgille07 · Jan 26, 2013 · Viewed 9.1k times · Source

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.

Answer

undefined picture undefined · Jan 26, 2013
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.