I have a parent jQuery object and a child jQuery element.
I'd like to see if the child is already contained within the parent. I was thinking of using jQuery's contains()
method. However, in Chrome and IE I always get true
returned and in FF6 I get an error apareDocumentPosition is not a function
Am I using this incorrectly? Is there a better way to achieve this?
Fiddle
Code:
<div class="metroContainer">
<div class="metroBigContainer">
<div id="big1" class="metroBig">
Stuffs 1
</div>
<div id="big2" class="metroBig">
Stuffs 2
</div>
</div>
<div class="otherContainer">
</div>
// I expect false, returns true
$.contains($('.metroBigContainer'), $('.otherContainer'))
I have a parent jQuery object and a child jQuery element.
I'd like to see if the child is already contained within the parent. I was thinking of using jQuery's contains()
method. However, in Chrome and IE I always get true
returned and in FF6 I get an error a.pareDocumentPosition is not a function
Am I using this incorrectly? Is there a better way to achieve this?
Fiddle
Code:
<div class="metroContainer">
<div class="metroBigContainer">
<div id="big1" class="metroBig">
Stuffs 1
</div>
<div id="big2" class="metroBig">
Stuffs 2
</div>
</div>
<div class="otherContainer">
</div>
// I expect false, returns true
$.contains($('.metroBigContainer'), $('.otherContainer'))
Share
Improve this question
asked Sep 23, 2011 at 20:04
Mike FieldenMike Fielden
10.2k14 gold badges60 silver badges100 bronze badges
3
-
I think it may be because
contains()
takes a DOM element, and what you are passing it is a jQuery object. – Jack Commented Sep 23, 2011 at 20:07 - 1 I do not see a closing </div> for metroContainer. Maybe that is causing jquery to bee confused about which div is contained within the other divs – dave Commented Sep 23, 2011 at 20:10
- @dave I believe the browser uses a 'stack' model for assigning closing div tags to opening tags; that is, a closing tag closes the most recent open tag. In other words, metroContainer would contain everything, and the actual DOM structure would match the clear intent in this case. – Asmor Commented Sep 23, 2011 at 20:17
2 Answers
Reset to default 8I believe contains takes dom elements, not jquery objects:
$.contains($('.metroBigContainer')[0], $('.otherContainer')[0])
also you could try testing the length
$('.metroBigContainer .otherContainer').length
if it is 1 (or greater then 1) then it exists if not then it doesn't exist.