0

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

etog
  • 1
  • 1
  • If the element isn't found then it doesn't exist at that time. What elements are found by that call to `getElementsByClassName`? How do they differ from what's expected? Is anything dynamically changing the DOM after the page is initially loaded? – David May 15 '23 at 11:53
  • use `appendChild` for javascript and `append` for jQuery library – perona chan May 15 '23 at 11:55
  • Most likely the element is added to the DOM after the page had loaded. You can use a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to determine when the element is added to the page. – Nick Parsons May 15 '23 at 12:01

0 Answers0