Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing objects for ancestor/descendent relationship in JavaScript or Jquery

I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.

I've seen a model of testing for

$b.parents('nodename').length>0

Which is fantastic when you only need to check if an element is a child of any node by that name.

But what about a specific node? You can't test

$b.parents($a).length>0

Because jQuery parents takes a nodename expression as an argument to filter.

As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.

Thanks!

like image 627
dreisch Avatar asked Nov 13 '08 18:11

dreisch


1 Answers

a.contains(b)

This is a pure JavaScript solution using Node.contains. The function is inclusive, a.contains(a) evaluates to true.

There's an edge case in IE9: if b is a text node, contains will always return false.

like image 91
Alexey Lebedev Avatar answered Nov 11 '22 15:11

Alexey Lebedev