Search code examples
javascripthtmlxpath

Select a HTML element containing APOSTROPHE using document.evaluate()


I am trying to select an element containing 1'000 g using document.evaluate(). The issue is the apostrophe. I tried to use \u0027, '', \', \\' and ', but those either trigger invalid xpath expression errors or return no elements.

const items1 = document.evaluate(
  "//p[contains(normalize-space(.), '1000\u00a0g')]",
  document,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null,
);
console.log("item1", items1.snapshotItem(0).textContent);

const items2 = document.evaluate(
  "//p[contains(normalize-space(.), '1'000\u00a0g')]",
  document,
  null,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
  null,
);
console.log("item2", items2.snapshotItem(0).textContent);
<p>1000&nbsp;g</p>
<p>1'000&nbsp;g</p>

What is the correct way to select an element containing an apostrophe using an xpath expression in document.evaluate()?


Solution

  • To include an apostrophe in the 'contains' section of your XPath you need to use it as a literal character and wrap the string to find in double quotes, which you have to esape using \" from the outer string:

    const items1 = document.evaluate(
      "//p[contains(normalize-space(.), '1000\u00a0g')]",
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null,
    );
    console.log("item1", items1.snapshotItem(0).textContent);
    
    const items2 = document.evaluate(
      "//p[contains(normalize-space(.), \"1'000\u00a0g\")]",
      document,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null,
    );
    console.log("item2", items2.snapshotItem(0).textContent);
    <p>1000&nbsp;g</p>
    <p>1'000&nbsp;g</p>