Polymer2 Shadow dom select 子元素

Polymer2 Shadow dom select child element

我正在研究 polymer2 阴影 dom 模板项目需要 select 来自父元素的子元素。我发现这个 article 引入了一种方法来 select 子阴影 dom 像这样的元素:

// No fun.
document.querySelector('x-tabs').shadowRoot
        .querySelector('x-panel').shadowRoot
        .querySelector('#foo');

// Fun.
document.querySelector('x-tabs::shadow x-panel::shadow #foo');

然而,当我在我的 polymer2 项目中尝试时,像这样:

    //First: works!!
    document.querySelector('container')
                        .shadowRoot.querySelector('app-grid')
                        .shadowRoot.querySelector('#apps');
   //Second: Doesn't work!// got null
document.querySelector('container::shadow app-grid::shadow #apps')
// Thrird: document.querySelector('* /deep/ #apps') // Doesn't work, got null

我很需要第二种方式或者第三种方式,把selector放在()里面,但是都不行。有谁知道为什么第二个不起作用?非常感谢!

::shadow 和 /deep/ 从未(?)在 Firefox 中工作,并且在 Chrome 63 及更高版本中是堕落的。

Source


Eric Biedelman 编写了 nice querySelector method 用于使用阴影 DOM 在页面上查找所有自定义元素。我自己不会使用它,但我已经实现了它,因此我可以 "querySelect" 在控制台中自定义元素。这是他修改后的代码:

// EXAMPLES
// findCustomElement('app-grid')        // Returns app-grid element
// findCustomElements('dom-if')         // Returns an array of dom-if elements (if there are several ones)
// findCustomElement('app-grid').props  // Returns properties of the app-grid element

function findCustomElement(customElementName) {
  const allCustomElements = [];

  customElementName = (customElementName) ? customElementName.toLowerCase() : customElementName;

  function isCustomElement(el) {
    const isAttr = el.getAttribute('is');
    // Check for <super-button> and <button is="super-button">.
    return el.localName.includes('-') || isAttr && isAttr.includes('-');
  }

  function findAllCustomElements(nodes) {
    for (let i = 0, el; el = nodes[i]; ++i) {
      if (isCustomElement(el)) {
        el.props = el.__data__ || el.__data || "Doesn't have any properties";

        if (customElementName && customElementName === el.tagName.toLowerCase()) {
          allCustomElements.push(el);
        } else if (!customElementName) {
          allCustomElements.push(el);
        }
      }
      // If the element has shadow DOM, dig deeper.
      if (el.shadowRoot) {
        findAllCustomElements(el.shadowRoot.querySelectorAll('*'));
      }
    }
  }

  findAllCustomElements(document.querySelectorAll('*'));

  if (allCustomElements.length < 2) {
    return allCustomElements[0] || customElementName + " not found";
  } else if (customElementName) {
    allCustomElements.props = "Several elements found of type " + customElementName;
  }

  return allCustomElements;
}

删除if (isCustomElement(el)) {语句,您可以查询选择任何元素,如果存在多个元素,则获取它的数组。您可以更改 findAllCustomElements 以使用 shadowDoom 上的递归循环作为基础来实现更智能的 querySelect。同样,我自己不会使用它——而是将变量从 parent 元素传递到 children,其中 children 具有激活特定行为的 observers – 但是如果没有其他方法,我想给你一个回退的一般实现。

你的问题的问题是你没有给出任何关于你为什么要首先 select children 的细节。