Reputation: 1745
i am noticing a bug in jquery find.
if i call foo.find with a selector that might reference foo itself, it won't work. example here.
http://jsfiddle.net/CgfPj/6/ (EDIT: UPDATED THE fiddle to more clearly explain what i'm trying to do)
test.find should be able to find a span that is a child of a div, but it can't seem to since the div is test itself. is this a bug?
Upvotes: 1
Views: 92
Reputation: 70169
#test
is the div
you're referencing.
.find()
returns the descendants of #test
matching your given selector. #test
has no descendant div
s, hence test.find("div > span")
doesn't match any elements.
To get the direct span
descendants of #test
you should use:
test.find("> span")
Edit as per OP edit:
$("#test > span, #test div > span")
Will get all span
s direct descendant of #test
as well as all span
elements direct descendant of div
s inside of #test
- fiddle.
There's no such thing as a :parentIs(div)
selector in the CSS selectors spec nor in jQuery as far as I'm aware of, but you can easily fill that gap by using a filter function:
var spans = test.find('span').filter(function() {
return $(this).parent()[0].tagName.toLowerCase() === 'div';
});
$("#result").text(spans.length);
Upvotes: 1
Reputation: 55750
<div id="test">
<span>hello</span>
</div>
$("#result").text(test.find("div > span").length)
The Output that length = 0 is absolutely right.. That is not a bug but the expected behavior.
You span is nested inside the div with #test
test.find("div > span")
// is trying to find a span which is a child of div nested inside #test div.. Because it has no div inside #test this will give you 0.
The HTML in this case which will return 1 is
<div id="test">
<div>
<span>hello</span>
</div>
</div>
Upvotes: 0
Reputation: 36947
If I am looking at this right..
var test = $("#test");
$("#result").text(test.find("div > span").length)
$("#result2").text($("div > span").length)
By defining test
as the element that is the div itself. Your essentially telling find
to look for another div with a span in that div. Try
$("#result").text(test.find("span").length)
Upvotes: 0