1

I have an input element nested inside my custom element and I want to tamper the input element from my custom element. I don't want to use shadow DOM and slots to do it.

Example in Codepen

Example in Github

connectedCallback () {
  const template = document.createElement("template");
  template.innerHTML = templateDiv;
  this.appendChild(template.content);

  console.log(this.querySelector('input'))
  console.log(this.firstElementChild)
}

Everything works OK on Firefox. But on Chromium, I can not access the child element from the custom element. When querying for the input element with this.querySelector, I just get null on Chromium.

Could this be considered as a bug in Chromium or is it just that Firefox does more than it should?

jutunen
  • 23
  • 2
  • The `` element would solve your problem. Could you explain why you don't want to use it? – Emiel Zuurbier Nov 03 '19 at 00:13
  • @EmielZuurbier I would have to introduce shadow DOM in to my code. I'd like to keep things as simple as as possible... – jutunen Nov 03 '19 at 00:23
  • Yes that is true. There is a "hacky" way to do it, but I would still encourage you to use the Shadow DOM as it does what you want in a really great way. But that depends on you. – Emiel Zuurbier Nov 03 '19 at 00:44
  • where you get ``null`` and expect a value... wrap your console.logs inside a ``setTimeout( func , 0)`` to delay execution till new nodes are really ready in the DOM. Long explanation is about Chromium/V8 and Event Loops I only half understand. Layman's answer is: your 5 codelines in the same scope are somehow optimized by the browser engine and the DOM nodes are only created after those 5 lines executed. ``setTimeout`` makes sure code executes after the eventloop has finished.. or something like that..It is not specifically Custom Elements related – Danny '365CSI' Engelman Nov 03 '19 at 12:02
  • Thank you @Danny'365CSI'Engelman for your insight, I did a quick test, and you're right! I wonder whether I now have to try to build some fancy asynchronous handling for getting the child element. – jutunen Nov 03 '19 at 14:48
  • Nothing fancy, ``setTimeout`` is enough. I use it in many ``connectedCallbacks`` – Danny '365CSI' Engelman Nov 03 '19 at 19:32
  • @Danny'365CSI'Engelman you're right, again. There is not much official documentation for setTimeout with zero delay. But I found this: https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – jutunen Nov 04 '19 at 15:17
  • Good deep-dive video at: https://www.youtube.com/watch?v=8aGhZQkoFbQ keyphrase: *"it can't do a render if there is code on the stack"* – Danny '365CSI' Engelman Nov 06 '19 at 09:21

0 Answers0