1

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,009
  • 2
  • 13
  • 33

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
  • 20,849
  • 6
  • 20
  • 43
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
  • 4,584
  • 4
  • 25
  • 48