# Match an expression that has a descendant pattern

I have a complicated expression in which I have another expression p which, when it’s present, I want to match the outer expression and all of its children. I was hoping for something like Descendant[p] which matches p if it appears anywhere in the child tree of the expression. For example:

X = ElementA[a,b,c,
ElementB[{1,2,3,
ElementC[c,d,
ElementD[foo]
]
}]
]


Where:

MatchQ[X, ElementA[Descendant[foo]]]


Would match the entire expression ElementA[...] because foo appears somewhere as a descendant.

• Something like MatchQ[X, e : ElementA[args__] /; ! FreeQ[e, foo]]? – J. M. will be back soon Mar 14 at 2:59
• ... or MatchQ[X, _ElementA?(Not@*FreeQ[foo])] – kglr Mar 14 at 3:15