Find the ONLY the next, innermost parent element above contains() target element

Find the ONLY the next, innermost parent element above contains() target element

It occurs sometimes that I want to execute a function only on the next, innermost, certain element above a matching element. Simplified example:

  1. <div    ....>
  2. .....
  3. <div .....>
  4. <a ....>
  5. foobar
  6. </a>
  7. ...
  8. </div>
  9. ....
  10. </div>

Only the innermost <div> should be removed.

Therefore I coded in  the past:

$("div:contains('foobar')").eq(($("div:contains('foobar')").length) - 1).remove();

It works.

However I wonder if there is a shorter way for this condition.

The alternative way should also work if there is only 1 or no <div>. In the last case nothing should be removed.

Any suggestions?