I am getting started with Web Components and want to get all elements where the tag name ends in "-component", in order to register them as custom tags.
For best performance, I want to use querySelectorAll and not iterate over all elements.
However, as you can see in the following example [tag$="-component"]
does not find the elements.
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>';
}
<my-component>
<hello-world-component>
<h1>Hello, world!</h1>
</hello-world-component>
</my-component>
<div class="result"></div>
If anyone knows what is going on and could let me know or if anyone knows if this is even possible it would be greatly appreciated.
The CSS syntax $=
applies to element attributes, not to elements themselves.
There is no syntax to create a CSS selector that matches elements that have a certain suffix.
However, if the purpose is to find custom elements that have not been registered yet, you can use the :defined
selector:
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>';
}
<my-component>
<hello-world-component>
<h1>Hello, world!</h1>
</hello-world-component>
</my-component>
<div class="result"></div>