selecting text by ignoring inner Elements of div tag javascript

后端 未结 2 1510
陌清茗
陌清茗 2021-01-19 06:49




        
2条回答
  •  被撕碎了的回忆
    2021-01-19 07:21

    This is much easier in IE using TextRange, which is based around characters, words and sentences rather than nodes and offsets. In non-IE browsers, you'll need to do tedious manual traversal of text nodes in the DOM. However, even if you were to do this to get the first ten text characters within your

    (which would be "asdf asdfa"), your strategy is flawed because you're using a replacement on innerHTML, which would try and fail to find "asdf asdfa" (innerHTML would start with "asdf asdfa", or possibly "asdf as", depending on browser).

    What I would suggest is doing the DOM traversal to find all text nodes within the

    and surrounding the parts of the text nodes you need with s, thus avoiding Ranges altogether and therefore making this work in all major browsers.

提交回复
热议问题