I am attempting to create a list of "div" tags located inside of a parent node, which is accessed via document.querySelector('#parent-ID').
if (document.readyState !== 'loading') {
let base = document.querySelector("#notion-app");
let child = base.getElementsByTagName("div");
console.log(child);
console.log(child.length);
} else {
document.addEventListener("DOMContentLoaded", () => {
// same as above
})
}
Both base and child seem to be being called correctly within the first if(). console of child And toward the bottom of this console output, the length is listed as 385. length of child
However, when I try to log child.length, it returns the number 0. As some blogs or Q&As have suggested, I have also tried Array.prototype.slice.call(child) && for (let i=0; i<child.length; i++){}, but neither has worked for me.
Can someone please advise what I am doing wrong?
UPDATE - I managed to make the code work, but still do not understand why it wasn't working.
The original structure of my code was creating a new instance of the mutation observer to listen to changes to the DOM, adding buttons to the document via insertAdjacentHTML(), and then using if(document.readyState === ...) to get the HTMLCollection and converting to an array to iterate through later on.
The solution was to simply remove either the inserAdjacentHTML command or the document.readyState condition. Then the length and any other method was successfully callable.
My problem is that regardless of whether I made these changes or not, console.log of document.readyState ALWAYS returned complete. So, according to my understanding, it shouldn't have mattered whether there was DOM manipulation or an if condition...
Anyway, that's how it worked for me and if anyone can point out what it is I am missing, I would kindly appreciate any comments.