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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With