Search code examples
javascriptxpathselenium-webdriverapostrophe

JavascriptExecutor XPath with apostrophe


I'm trying to find a text element using XPath using JavascriptExecutor. The problem is that the text has an apostrophe, and I don't know how to escape it in this case. Normally it is just enough with \". Could you help me?

I have already tried the following options:

((JavascriptExecutor)driver).executeScript("var path = '//*[text()=\"d'arrivée\"]/following-sibling::div/div';
var x = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;x.style.display='block';");`

and

((JavascriptExecutor)driver).executeScript("var path = '//*[text()=\"d\"arrivée\"]/following-sibling::div/div';
var x = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;x.style.display='block';");`

Solution

  • Try below expression with escaped apostrophe:

    '//*[text()="d\'arrivee"]/following-sibling::div/div'
    

    When using a string between single quotes, you should escape an apostrophe with a single backslash. Double quotes don't need to be escaped in this type of string.