Skip to content

can't use in web component #188

@alifeee

Description

@alifeee

here is my web component

class ChairComparison extends HTMLElement {
  constructor() {
    super();
    this.root = this.attachShadow({ mode: "closed" });
  }
  connectedCallback() {
    this.render();
  }

  render() {
    const image1src = this.getAttribute("src1");
    const image2src = this.getAttribute("src2");

    const div = document.createElement("div");
    div.setAttribute("id", "slider");
    this.root.appendChild(div);

    let slider = new juxtapose.JXSlider(
      div,
      [
        {
          src: image1src,
        },
        {
          src: image2src,
        },
      ],
      {}
    );

    const link = document.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute(
      "href",
      "https://cdn.knightlab.com/libs/juxtapose/latest/css/juxtapose.css"
    );
    this.root.appendChild(link);
  }
}

customElements.define("chair-comparison", ChairComparison);

Juxtapose uses document.querySelector which is not available on web components (as they are not found in the document, but their own shadow.

I fixed it with the following commit

alifeee/blog@393fd78

- this.wrapper = document.querySelector(this.selector);
+ // if selector is a DOM element, use it directly
+ if (this.selector instanceof Element) {
+   this.wrapper = this.selector;
+ } else {
+   this.wrapper = document.querySelector(this.selector);
+ }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions