Remove Element Found with Xpath in Javascript

Viewed 997

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.

2 Answers

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.

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.

Related