auto-complete-element
auto-complete-element copied to clipboard
Input cannot be found if javascript is run before element is present
I had some issues getting started with this module as the input could not be found when the element is connected.
Debugging I found it was due to https://github.com/github/auto-complete-element/blob/5574169a6c7fc000e5e532e3a43d2ce7aea11ff6/src/auto-complete-element.js#L19
It was then I realised that the javascript needs to be run after the element is on the page. I was able to verify this by changing the example provided such that the javascript tag was in the head of the page.
Should there be a console log or should this case be handled?
I suspect that this might mean this element cannot be added to the page dynamically if the javascript is already present.
Love this element, but I've the same problem with Rails Webpacker. Input can't be found if my js pack is in the head. Because I use turbolinks I need JS in the head.
The Problem here JavaScript need to loaded after All elements are loaded.
I had some issues getting started with this module as the input could not be found when the element is connected.
Debugging I found it was due to
https://github.com/github/auto-complete-element/blob/5574169a6c7fc000e5e532e3a43d2ce7aea11ff6/src/auto-complete-element.js#L19
It was then I realised that the javascript needs to be run after the element is on the page. I was able to verify this by changing the example provided such that the javascript tag was in the head of the page.
Should there be a console log or should this case be handled?
I suspect that this might mean this element cannot be added to the page dynamically if the javascript is already present. I think the only way is write it in the head and body too🎈
The issue comes from the usage of document.getElementById, which fails to find the element if it's not in the document yet, or auto-complete is part of ShadowDOM of another element.
Replacing usage of document.getElementById with element.querySelector fixes the issue.
I'll make a PR.