Reputation: 9340
I'm curious why the jQuery expression
$("#mydiv").find(".myitem1") || $("#mydiv").find(".myitem2");
returns []
if:
.myitem1
doesn't exist on the page. Also, $("#mydiv").find(".myitem2")
DOES exist, the result is a non-empty object.
I expect to get the result that is the first expression if it exists otherwise the second one. As you see I use ||
. What am I doing wrong?
Upvotes: 0
Views: 42
Reputation: 93571
The explanations of why it fails are in the comments, but, given the logic you are attempting, why not just use this (if they are in the page in sequential order):
$("#mydiv").find(".myitem1,.myitem2").first();
otherwise use:
var $result = $("#mydiv").find(".myitem1");
if (!$result.length){
$result = $("#mydiv").find(".myitem2");
}
Do not use a ternary expression as-is as it will run the first selector twice. Use a ternary like this:
var $result = $("#mydiv").find(".myitem1");
$result = $result.length ? $result : $("#mydiv").find(".myitem2");
Your current code assumes find
returns nothing if a match isn't found, but that is not how jQuery allows for chaining of methods. It will always return a jQuery object (just an empty one for no matches). This allows jQuery code like $('#youCantMatchThis').text();
to return an empty string and not give an error.
Upvotes: 1