JS DOM: Get elements by text content

前端 未结 3 923
天命终不由人
天命终不由人 2020-12-09 05:12

I am looking for a way to perform fulltext search on the DOM tree with JS. In two words, I would like to retrieve the list of text nodes which contain a given string.

<
相关标签:
3条回答
  • 2020-12-09 05:30

    In general DOM: For getting element by text in DOM

    //*[text()='anytext']
    

    or

    //*[.='anytext']
    
    0 讨论(0)
  • 2020-12-09 05:36

    Will 'contains' selector from jquery solve the problem?

    http://api.jquery.com/contains-selector/

    0 讨论(0)
  • 2020-12-09 05:52

    If you have a modern browser, you can always use XPATH, since it has content-based search.

    This is an example:

    document.evaluate('//*[text()="' + string + '"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE).snapshotItem(0);
    

    And with older browsers, you can shim XPATH in with something like http://llamalab.com/js/xpath/

    0 讨论(0)
提交回复
热议问题