如何选择以特定字符串结尾的标签?

Ood*_*Ood 5 html javascript web-component

我正在开始使用 Web 组件,并希望获取标签名称以“-component”结尾的所有元素,以便将它们注册为自定义标签。

为了获得最佳性能,我想使用 querySelectorAll而不是迭代所有元素

但是,正如您在下面的示例中看到的那样,[tag$="-component"]没有找到该元素。

const components = document.querySelectorAll('[tag$="-component"]');
const result = document.querySelector('.result');

result.innerHTML = 'Search started<br>';

for(var i = 0; i < components.length; i++){
 
  result.innerHTML = result.innerHTML + components[i].tagName + '<br>';
 
}
Run Code Online (Sandbox Code Playgroud)
<my-component>

  <hello-world-component>
  
    <h1>Hello, world!</h1>
  
  </hello-world-component>

</my-component>

<div class="result"></div>
Run Code Online (Sandbox Code Playgroud)

如果有人知道发生了什么事并且可以让我知道,或者如果有人知道这是否可能,我将不胜感激。

tri*_*cot 1

CSS 语法$=适用于元素属性,而不适用于元素本身。

没有语法可以创建匹配具有特定后缀的元素的 CSS 选择器。

但是,如果目的是查找尚未注册的自定义元素,则可以使用:defined选择器:

const components = document.querySelectorAll(':not(:defined)');
const result = document.querySelector('.result');

result.innerHTML = 'Search started<br>';

for(var i = 0; i < components.length; i++){
  result.innerHTML = result.innerHTML + components[i].tagName + '<br>';
}
Run Code Online (Sandbox Code Playgroud)
<my-component>
  <hello-world-component>
    <h1>Hello, world!</h1>
  </hello-world-component>
</my-component>
<div class="result"></div>
Run Code Online (Sandbox Code Playgroud)