I am trying to make a chrome extension. I try to create a div and put it at the top of my notifications popup on youtube that we open by clicking on this button.
So I try to catch the first child of my container and make a insertBefore. But I have a problem : I can't get the firstChild element of my container, or it is always null.
I try this code, but I don't know if it's the good way :
const notificationsContainer = document.querySelector("#container > #sections");
notificationsContainer.style.backgroundColor = "blue"; //to view my container
/* Creation of my new div */
let newDiv = document.createElement("div");
newDiv.style.backgroundColor = "green";
newDiv.style.height = "50px";
newDiv.style.width = "50px";
newDiv.style.top = "0";
/* Insert my newDiv */
let parentElement = document.querySelector("#items");
let childElement = parentElement.firstChild;
parentElement.insertBefore(newDiv, childElement);
This is when I print my parentElement and childElement in the console (they are empty) : console print
Thank you for your help !
P.S. I'm trying to get my notifications so I scrap them with js, if you know a better way I'd be happy to listen to it.
Edit : Here an inspector screenshot focuses on the selected elements.
Are you sure the the element you're targetting has a child element? If it does not, .firstChild will return null.
There might be an issue with timing. The element is empty when you grab it and filled after that.
Maybe you need to wait for "some time".
Try to grab item after couple of seconds by setting the timeout (setTimeout).