5

I'm writing a JavaScript function that can be used to replace text with HTML code, but to do this I need to be able to access text in text node form. The following XPath selects all div tags in a document:

//div

The following XPath selects all elements with the attribute class assigned the value myclass:

//*[@class="myclass"]

The following selects all of the text (not text nodes) that occurs at any level underneath the element with the ID comments:

//*[@id="comments"]//text()

What is an XPath that can be used to select all text nodes under any element? So, say I want to replace all the non-comment occurrences of the string Hebert and I need all of the text nodes so I can scan through them for that string. Would it use text() in the query?

Melab
  • 2,594
  • 7
  • 30
  • 51
  • Element nodes have text nodes in it, that you can manipulate. Are you referring to Element nodes that only have text and no child Element nodes in it? – Balazs Vago Mar 10 '17 at 16:04
  • 8
    ***You really ought to [accept](http://meta.stackoverflow.com/q/5234/234215) some of the fine answers you've received to the 75 questions you've asked.*** Asking **75 questions and accepting 0 of the fine answers you've received** (and only ever upvoting twice in 4 years) shows a lack of appreciation for the help you've received and failure to help future readers. It's not too late to fix this situation. You should do so now. – kjhughes Mar 11 '17 at 15:51

1 Answers1

9

Two options:

  • To select all text nodes whose string value contains the substring "Herbert":

    //text()[contains(.,'Herbert')]
    
  • To select all text nodes whose string value is "Herbert":

    //text()[.='Herbert']
    

Note that your comment,

The following selects all of the text (not text nodes)

regarding the XPath, //text(), is incorrect. The node test text() selects text nodes. In a string context, it will return the string-value of the text node, but text() alone most certainly selects actual text nodes.

See also Testing text() nodes vs string values in XPath

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240