Why my element undefined in code but defined if I run the code in console js?

24 Views Asked by At

I'm trying to add a button to an element on YouTube with the following code:

document.addEventListener('DOMContentLoaded', function() {
  let elm = document.getElementsByClassName("style-scope ytd-guide-section-renderer")[8];
  let nbutton = document.createElement("button");
  elm.append(nbutton);
}, false);

Unfortunately, I'm always getting the error:

cannot read properties of undefined (reading 'append')

When I run the code in console, after the page is loaded, everything works fine.

I thought, the problem is, that the page isn't fully loaded before I'm trying to access the element, so I added a page load event listener, but It's still not working.

No other question helped me, I think it's a specific issue of the YouTube page, so please don't mark my question as duplicate

0

There are 0 best solutions below