Reputation: 8541
I have a line of jQuery code that is causing an error as I placed two periods in front of the b class. I am wondering how does jQuery interpret the following line? If I had only one period in front of b instead of two, I assume that jQuery interpret it as: "if class b exists within class a which exists in the parent of this, alert prompt hi".
if ( $(this).parent().find(".a ..b") ) {
alert("hi");
});
Upvotes: -1
Views: 115
Reputation: 700830
That might depend on the browser. Both in Internet Explorer 9 and Firefox 10.0, the selector will just find nothing, and you get back an empty jQuery object.
As you are using the jQuery object as the condition in the if
, the code inside the if
will always run. A jQuery object is always a non-falsy value, so the condition will always be evaluated as true
, regardless of whether jQuery found anything from your selector.
If you want to check if something was found, use the length
property:
if ( $(this).parent().find(selector).length ) {
Upvotes: 3
Reputation: 1039488
.a ..b
is an invalid selector and it will throw error:
Uncaught Error: Syntax error, unrecognized expression: .
.a .b
is the correct selector.
So $(this).parent().find(".a .b")
will first fetch the direct parent node of this
, then it will search for a descendant element with the class="a"
and then another descendant element within with the class="b"
, and if it finds it will alert hi
.
Upvotes: 8