Xpath Search Through Html Tags
Solution 1:
Yes. You can use normalize-space()
for this. (line-wrapped for the sake of readability)
var xpath = "
//*[
contains(
translate(
normalize-space(.),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz'
),
normalize-space('" + searchTxt.toLowerCase() + "')
)
]
";
Note that this will find the entire hierarchy of nodes that contain the respective text, up to and including the <html>
element. You would be interested in the "most deeply nested" node, I guess.
Also note that you might want to remove single quotes from searchTxt
as they would break the XPath expression.
Solution 2:
There is probably also a recursive method that looks at the textContent/innerHTML of a root element to see if a match is found. If so, go down firstChild nodes that match and so on, following children until the match fails, at which point the element containing the text has been found.
Should also work for multiple matches with the text.
XPath might be faster, but perhaps not as wildely supported (though it seems to be on all modern browsers).
Post a Comment for "Xpath Search Through Html Tags"