25

I'm using Selenium WebDriver(ChromeDriver). I need to remove some elements from page after processing(from DOM model).

For example I have a following element:

WebElement starRatingElement = reviewElement.findElement(By.className("review-info-star"));

How to remove starRatingElement from browser DOM model ?

How it can be achieved in Java with Selenium WebDriver ? Please show an example.

alexanoid
  • 24,051
  • 54
  • 210
  • 410

1 Answers1

36

You'll have to execute a JavaScript code to make any DOM changes.

WebDriver driver = new ChromeDriver();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
    js = (JavascriptExecutor) driver;
}
js.executeScript("return document.getElementsByClassName('review-info-star')[0].remove();");
JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
  • 2
    Just a note of clarification... this doesn't actually remove the element from the DOM, it just hides it (makes it not visible). – JeffC Oct 18 '15 at 17:14
  • 1
    Thanks @JeffC and alexanoid for the correction. I've made the changes to the answer. – JRodDynamite Oct 18 '15 at 17:50
  • 4
    `getElementsByClassName()` returns an `HTMLCollection`, which does not have a `remove()` method -- could use `document.getElementsByClassName('review-info-star')[0].remove()` – Ben Mordue Mar 22 '19 at 09:57
  • 2
    You can use: `document.querySelectorAll('.review-info-star').forEach(function(element) {element.remove();});` – anno Jun 19 '19 at 10:16
  • How do you send a variable with the name of the element you want to delete to the Javascript? – d-b Nov 07 '20 at 02:13