test connectedCallback DOM

by WebComponents

HTML

<!-- Your Component does not work when defined BEFORE DOM is parsed -->
<!-- Loaded ASAP (Like in the <head>) to prevent this UI generating component generating FOUCs -->
<script src="https://aarongustafson.github.io/form-show-if/form-show-if.js"></script>

<!-- wrap your Web Component in a TEST Web Component -->
<script>
  const comp_name = "form-show-if";
    customElements.define("test-"+comp_name, class extends customElements.get(comp_name){
      connectedCallback(){
          // in your connectedCallback you do:
          this.__$field = this.querySelector("input:not([type=submit],[type=reset],[type=image],[type=button]),select,textarea");
          // But the Web Component was defined earlier and the connectedCallback fires on the OPENING tag!
          // so there is no innerHTML parsed yet, your query returns nothing
          console.log("this.__$field", this.__$field?.nodeName, "because connectedCallback ran on opening tag");
          // if we wait a tick, the DOM parser parsed more DOM, thus your innerHTML is available
          setTimeout(() => {
            this.__$field = this.querySelector("input:not([type=submit],[type=reset],[type=image],[type=button]),select,textarea");
            // now you got the INPUT
            console.log("this.__$field", this.__$field?.nodeName, "available because querySelector executed after more DOM was parsed");
            super.connectedCallback();
            console.log("previous two statements are from your code")
          });
      }
   })
</script>

<form action="#">
  <label>Email address<input type="email" name="email" /></label>
  <br />
  <test-form-show-if conditions="email=*">
    <label for="dep1"
      >Depends on email<input
        name="dep1"
        id="dep1"
        aria-describedby="dep1-description"
    /></label>
    <small id="dep1-description"
      >This field will become required if the email field is filled out</small
    >
 ...