js manipulates DOM elements in shadow-root

1. Background

In the project, the shadow -root (open) was encountered in the DOM structure , and the DOM elements in it could not be directly obtained by using the JS method

Two, shadow DOM

An important property of Web components is encapsulation—the markup structure, style, and behavior can be hidden and isolated from other code on the page, ensuring that different parts do not mix together, making the code cleaner and tidier. Among them, the Shadow DOM interface is the key, it can attach a hidden, independent DOM to an element. The objects under the shadow-root package are not in the global DOM tree, so methods such as getElementById cannot get the objects in the package.

  • Shadow DOM is a tool for building component-based applications. Therefore, solutions are provided for common problems in web development:
  • Isolated DOM: The component's DOM is isolated (for example, document.querySelector() will not return nodes in the component's shadow DOM).
  • Scoped CSS: CSS defined inside the shadow DOM is within its scope. Style rules don't leak out, and page styles don't bleed through.
  • Composition: Design a declarative, markup-based API for components.
  • Simplified CSS - Scoped DOM means you can use simple CSS selectors, more generic id/class names without worrying about naming conflicts.
  • Efficiency - Think of your application as multiple DOM chunks rather than one big (global) page.

Shadow DOM is the same as normal DOM with two differences:

  • How it was created/used;
  • Behavior in relation to other parts of the page.

Typically, you create DOM nodes and attach them to other elements as children. With shadow DOM, you can create a scoped DOM tree that is attached to the element, but separate from its own real children. This scoped subtree is called the shadow tree. The attached element is called the shadow host.

The simple meaning is that it can be used to independently create a rendering block, which is not affected by the outer layer style, and the inner layer style does not affect the display of the outer layer.

3. Operate the elements in the shadow-root

1. First get the parent node of shadow-root, then use shadowRoot to get the shadow block of this parent node, and then you can operate

document.querySelector('#root').shadowRoot.querySelector('.chakra-portal')

2. Create a style tag under the shadow block and add styles in it

    let gtx = document.querySelector("#root");
    let style = document.createElement("style");
    style.innerHTML =
      ".grid_wrap { display: flex;justify-content: center;align-items: center;}";
    gtx.shadowRoot.appendChild(style);

 Related material: Using shadow DOM - Web Components | MDN

                   In-depth understanding of Shadow DOM v1 Develop Paper         

Guess you like

Origin blog.csdn.net/qq_44376306/article/details/128552574