How do I select text nodes with jQuery?

前端 未结 11 1527
独厮守ぢ
独厮守ぢ 2020-11-21 04:30

I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

11条回答
  •  礼貌的吻别
    2020-11-21 05:10

    If you can make the assumption that all children are either Element Nodes or Text Nodes, then this is one solution.

    To get all child text nodes as a jquery collection:

    $('selector').clone().children().remove().end().contents();
    

    To get a copy of the original element with non-text children removed:

    $('selector').clone().children().remove().end();
    

提交回复
热议问题