Using jQuery is there a way to find the farthest (deepest, or most nested) child element?

后端 未结 5 755
南笙
南笙 2020-12-11 11:25

If I have a set of elements:

Text 1
5条回答
  •  心在旅途
    2020-12-11 11:59

    Another method(possibly not so fast) with minimal lines of code could be as follows:

    var all_matched_elements = $(":contains('" + text_to_search + "')");
    var all_parent_elements = $(all_matched_elements).parents();
    var all_deepest_matches = $(all_matched_elements).not(all_parent_elements);
    

    This method is especially useful if your text is inside an element that also has other children elements as follows:

    Text 1Alpha Beta Gamma

    However, the above code would not work for a DOM that looks like following:

    search-text
    search-text

    In above case, it would only select inner-most with id "#aaa". It would drop id "#zzz". If one wants to also choose with id "#zzz" then code at the start has to be modified to drop elements from "all_parent_elements" whose direct text also matches search text.

提交回复
热议问题