Google Apps Script that removes a page element if it contains only the text

To create a Google Apps Script that removes a page element if it contains only the text “Search Text,” you need to follow these steps:

  1. Identify the Page Element: First, you need to identify the page element. This could be a div, span, p, etc. You need to know its tag and possibly a class name or ID to accurately select it.
  2. Check the Element’s Content: Once you have identified the element, you need to check if its content is exactly “Search Text”.
  3. Remove the Element: If the content matches, then remove the element from the page.

Here’s an example script that demonstrates this logic. Please adjust the elementSelector to target the specific element you’re interested in:

function removeElementIfContainsSpecificText() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();

  // Define the text to search for and the element selector
  const searchText = "Search Text";
  const elementSelector = "PARAGRAPH"; // Change this to DIV, SPAN, P, etc. as needed

  // Find and remove elements
  findAndRemoveElements(body, searchText, elementSelector);
}

function findAndRemoveElements(body, searchText, elementType) {
  let foundElement = body.findText(searchText);

  while (foundElement) {
    const element = foundElement.getElement();
    Logger.log(element.getText())
    const parentElement = element.getParent();


      parentElement.removeChild(element);


    // Find the next occurrence of the text
    foundElement = body.findText(searchText, foundElement);
  }
}

// Run the script
removeElementIfContainsSpecificText();

This script is a basic template. It searches for elements of the type specified by elementSelector within a Google Document that contain the text “Search Text” and removes them. You should adjust the elementSelector to match the type of element you are targeting (e.g., paragraph, text, etc.).

Remember, Google Apps Script works with Google Workspace applications like Docs, Sheets, and Slides. If you’re trying to manipulate a webpage that’s not part of Google Workspace, you would need a different approach, like using JavaScript in a web context.