0

So I'm building a multi form with tabs, however when I try to log the const: const breadcrumbs = document.querySelectorAll('.nf-breadcrumbs li');

It returns an empty NodeList, however when I use document.querySelectorAll('.nf-breadcrumbs li'); in the console it returns the correct NodeList.

I can't figure out why it behaves like this. Any help would be greatly appreciated!

EDIT: I've added defer to the script tag, it still give me an empty Array. Async seems to return the full NodeList sometimes but not consistently.

Image of the console

  • Does this answer your question? [document.querySelector always returns null](https://stackoverflow.com/questions/43947523/document-queryselector-always-returns-null) – Reyno Dec 08 '20 at 12:57
  • 2
    You're probably calling const `breadcrumbs = ...` too early, before the body tag in your html. So either move the script tag below the body or intercept the `window.onload` event and initialize the constant inside the callback handler. – obscure Dec 08 '20 at 13:03
  • Are you maybe loading the breadcrumb async? If it doesn't exist when the code runs, you will get the error you described. – Bjørn Nyborg Dec 08 '20 at 13:08
  • So I've added async and defer, it now returns the correct NodeList sometimes. But sometime when I reload the page it doesn't. Scripts are already loaded before the end of the body tag. I've tried to add ```window.onload``` but it caused a ReferenceError. – mennobrein Dec 08 '20 at 13:08
  • If you want us to help you show us your js code(don't tell us) because we can't be sure that what you tell us is what really happens. Also if you want to use an event for when HTML is loaded use DOMContentLoaded, load event waits for external files, images and so on and I guess it is not needed in your case. – George Pandurov Dec 08 '20 at 13:32
  • @GeorgePandurov It's literally just that one const. Whenever I add a onload method or eventlistener it give me a ReferenceError. I use WordPress as CMS – mennobrein Dec 08 '20 at 13:37
  • You are probably getting reference error because you are using your variable before initialising it but if you don't post your code here I can't tell you for sure. – George Pandurov Dec 08 '20 at 13:45
  • @GeorgePandurov ```window.addEventListener('DOMContentLoaded', () => { const breadcrumbs = document.querySelectorAll('.nf-breadcrumbs li'); console.log(breadcrumbs) })``` – mennobrein Dec 08 '20 at 13:53
  • There are no issues here, if you get `ReferenceError` it is probably coming from different line in your code. Maybe search for `breadcrumbs` and see if you are calling it before entering here in `DOMContentLoaded` callback – George Pandurov Dec 08 '20 at 14:10
  • I changed 'breadcrumbs' to a more unique name but it doesn't work. – mennobrein Dec 08 '20 at 14:37

0 Answers0