Home > Enterprise >  How to delete DOM element from Selenium Java
How to delete DOM element from Selenium Java

Time:11-26

I am trying to delete an element from a website using Selenium and Java, I have the xpath of the element

WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'discord.gg/')]"));

Thats the element I have. I want to delete it. I tried

$("//*[contains(text(),'discord.gg/')]").remove();

But that doesnt work either.

Thanks

CodePudding user response:

Try this:

WebElement m = driver
    .findElement (By.xpath ("//*[contains(text(),'discord.gg/')]"));
JavascriptExecutor js = (JavascriptExecutor)driver; 
js.executeScript("arguments[0].remove();", m);

CodePudding user response:

I used selenium only in python, and in there I used method to execute javascript in the driver context. Try this. Inside javascriptExecutor run this javascript (change accordingly):

var badTableEval = document.evaluate (
    "//body/center/center/table",
    document.documentElement,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
);

if (badTableEval  &&  badTableEval.singleNodeValue) {
    var badTable  = badTableEval.singleNodeValue;
    badTable.parentNode.removeChild (badTable);
}
  • Related