Home > database >  Accessing child element with JQuery in connectedCallback (Web Compoenent)
Accessing child element with JQuery in connectedCallback (Web Compoenent)

Time:10-31

I have a very simply Web Compoenent as follows which loads a the compoenent template file from the server:

export default class EditorComponent extends HTMLElement {
    async connectedCallback() {
        let file = "http://blog/components/editor/editor.html";
        let res = await fetch( file );
        this.attachShadow( { mode: 'open' } ).innerHTML = await res.text();
    }
}

customElements.define('editor-component', EditorComponent);

I need to access the child elements in the component HTML file via jQuery. I have tried the following but to no avail:

async connectedCallback() {
    let file = "http://blog/components/editor/editor.html";
    let res = await fetch( file );
    this.attachShadow( { mode: 'open' } ).innerHTML = await res.text();
    $(this).find('div').hide(); <<<<< WHAT I AM ATTEMPTING
}

I Have also added a timeout but that also did not help.

Can this be done?

CodePudding user response:

You have to do the jQuery syntax yourself

I am doing normal standard JS selectors here
Because I unlearned jQuery selectors (requiring a 80KB library) when IE9 was released... in 2011

It is a bit blunt to load HTML, display it in shadowDOM,
and then extract only the content you want. See h1 below

The standard DOMParser() can take a share of the work, faster because no HTML is Rendered,
see alink in:

<web-component></web-component>

  <script>
    customElements.define("web-component", class extends HTMLElement {
      async connectedCallback() {
        let file = "https://load-file.github.io/";
        let html = await (await fetch(file)).text();

        // Browser engine parses HTML to visual (shadow)DOM
        this.attachShadow({mode: 'open'}).innerHTML = html;
        let h1 = this.shadowRoot.querySelector("h1");

        // Browser engine parses HTML in Memory
        let doc = new DOMParser().parseFromString(html, "text/html");
        let alink = doc.querySelector("h2 a");
        alink.target = "blank" ;

        this.shadowRoot.replaceChildren(h1, "SHIFT Click this link: ",  alink);
      }
    })
  </script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Read up on all methods in:

  • Related