2

I am building a Chrome Extension. Trying to remove a HTML element which contains certain text. Have found the element using Xpath. But the element doesn't remove, and there is no error message.

<div>
     <div>Some Text</div>
</div>

let element = document.evaluate("/*[text() = 'Some Text']", document, null, XPathResult.ANY_TYPE, null)
element.remove();

This runs, but the element is not deleted.

Mr. J
  • 1,524
  • 2
  • 19
  • 42

2 Answers2

1

Change

let element = document.evaluate("/*[text() = 'Some Text']", document, null, XPathResult.ANY_TYPE, null)

to

let element = document.evaluate("//*[text() = 'Some Text']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
element.singleNodeValue.remove()

and see if it works.

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
0

document.evaluate does not return a DOM-node. It returns an XPathResult. See the docs here.

Also see this StackOverflow question for guidance on how to use JQuery with XPath.

leodriesch
  • 5,308
  • 5
  • 30
  • 52