skip to Main Content

I am trying to remove an element
For this purpose I am trying to make small plug in in .js
I have tailored this to this one specific google form I want to use it at, and for some reason I am haveing more issues in docs.google.com than I have in other websites

// content.js
const element = document.getElementsByClassName("xxxxxx");
element[0].remove(); 

"xxxxx" is the class of the block that holds the email display, I’ve changed it here, idk if one could pull the emails with it

When I paste the code in the console manually it works as I want it ,
but if I run it by plug in it gives me an error code:
"Uncaught TypeError: Cannot read Properties of undefined (reading ‘remove’)"

2

Answers


  1. I’m not really that skilled, but you may be getting that error because of all the nesting, try this.

    const element = document.getElementsByClassName("xxxxxx");
    element[0].innerHTML = "";
    element[0].remove();
    

    Also, make sure the website is fully loaded before your plugin executes the code.

    Login or Signup to reply.
  2. Looks like element[0] is undefined when you’re trying to access it’s remove() method.
    The plugin might be executing before the element is loaded onto the page.

    You could change the plugin code to wait for the page to load before calling the remove function that removes the element via DOMContentLoaded event or window.onload event.

    Something like the below:

    document.addEventListener('DOMContentLoaded', function() {
        const element = document.getElementsByClassName("xxxxxx");
        if (element.length > 0) {
            element[0].remove(); 
        } else {
            console.error("Element with class 'xxxxxx' not found.");
        }
    });
    

    So here it waits for the DOMContentLoaded event before calling remove().
    It also checks if the element with class "xxxxxx" exists before trying to remove it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search