JavaScript/jQuery: hasDescendant / hasAncestor

Hilariously, I’m having incredible difficulty finding any half-good way to determine whether or not an HTML element is inside another one or not — which seems like it should be a basic core feature of traversing and analyzing the HTML DOM. I was immensely surprised and disappointed that the “hasDescendant” (or likewise) method is missing.

I’m trying to do this:

var frog = $  ('#frog');
var walrus = $  ('#walrus');
if (frog.hasDescendant(walrus)) console.log("Frog is within walrus.");
else console.log("Frog is outside walrus.");

I’ve tried to reproduce what I’m looking for with many jQuery combinations.

walrus.is(frog.parents());
walrus.has(frog);
walrus.find(' *').has(frog);
frog.is(walrus.find(' *'));

I haven’t found a working solution yet.

This is becoming intensely frustrating to me at this point, as it’s extended what should have been a few seconds of work into hours of fruitlessly googling and raging.

Hopefully somebody will post up an obscure yet simple working solution before I get too deep into writing my own hasDescendant function. I will post the solution if I can find/write it.

I’m very disappointed in jQuery at the moment, and am glad we have communities like this to make up for these issues :)
//Chase.

newest questions tagged jquery – Stack Overflow

About Admin